0

I have a dataset like

df <- data.frame(year.id = c("2011.01","2011.02","2011.03",
                         "2013.01","2013.02","2013.03",
                         "2015.01","2015.02","2015.03"),
             values =c(20,25,30,
                       40,50,60,
                       70,80,90))

and I want to split this dataset if yearid starts with 2011/2013/2015 and what to get three datasets

 ##first df 
year.id values
2011.01     20
2011.02     25
2011.03     30
##second df 
2013.01     40
2013.02     50
2013.03     60
##third df
2015.01     70
2015.02     80
2015.03     90

many thanks in advance,

pogibas
  • 27,303
  • 19
  • 84
  • 117
Seyma Kalay
  • 2,037
  • 10
  • 22

2 Answers2

1

If you have the same data as shown you can extract the year part using regex and then use split

split(df, sub("\\..*", "", df$year.id))

#$`2011`
#  year.id values
#1 2011.01     20
#2 2011.02     25
#3 2011.03     30

#$`2013`
#  year.id values
#4 2013.01     40
#5 2013.02     50
#6 2013.03     60

#$`2015`
#  year.id values
#7 2015.01     70
#8 2015.02     80
#9 2015.03     90

If there are other years in the data and you want to extract only the ones mentioned

df$year <- sub("\\..*", "", df$year.id)
temp <- subset(df,  year %in% c(2011, 2013, 2015))
split(temp, temp$year)
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
1
df2011=df[grepl("2011",df$year.id),]
df2013=df[grepl("2013",df$year.id),]
df2015=df[grepl("2015",df$year.id),]
user2974951
  • 9,535
  • 1
  • 17
  • 24