Back

Explore Courses Blog Tutorials Interview Questions
0 votes
6 views
in R Programming by (50.2k points)

I have this data frame and I want to try to split them into other datasets based on year. Like "2020, 2021"

For example: "2020" ALL 2020 Year Values

"2021" ALL 2021 Year Values I named it: Dataset

Date    Left    Right   Up  Down  Middle  Size

1/1/2020    1   1   2   2   2   2

2/1/2020    1   7   8   9   8   8

3/1/2020    2   3   4   6   7   8

1/1/2021    1   2   2   2   2   7

2/1/2021    1   7   8   9   8   8

3/1/2021    2   3   4   6   7   8

1 Answer

0 votes
by (108k points)

In R programming you can simply extract the year from the date and after that just use the split() to get a list of dataframes for each year.

The data is:

df <- structure(list(Date = c("1/1/2020", "2/1/2020", "3/1/2020", "1/1/2021", 

"2/1/2021", "3/1/2021"), Left = c(1L, 1L, 2L, 1L, 1L, 2L), Right = c(1L, 

7L, 3L, 2L, 7L, 3L), Up = c(2L, 8L, 4L, 2L, 8L, 4L), Down = c(2L, 

9L, 6L, 2L, 9L, 6L), Middle = c(2L, 8L, 7L, 2L, 8L, 7L), Size = c(2L, 

8L, 8L, 7L, 8L, 8L)), class = "data.frame", row.names = c(NA, -6L))

The code is:

output <- split(df, format(as.Date(df$Date, "%d/%m/%Y"), "%Y"))

output

#$`2020`

#      Date Left Right Up Down Middle Size

#1 1/1/2020    1     1  2    2      2    2

#2 2/1/2020    1     7  8    9      8    8

#3 3/1/2020    2     3  4    6      7    8

#$`2021`

#      Date Left Right Up Down Middle Size

#4 1/1/2021    1     2  2    2      2    7

#5 2/1/2021    1     7  8    9      8    8

#6 3/1/2021    2     3  4    6      7    8

You can also achieve that using lubridate functions.

library(lubridate)

output <- split(df, year(dmy(df$Date)))

Related questions

Browse Categories

...