5

I would like to create multiple data frames and assign them based on years. I have seen other posts but I couldn't duplicate it for my case. For example,

a <- c(1,2,3,4)
b <- c('kk','km','ll','k3')
time <- (2001,2001,2002,2003)
df <- data.frame(a,b,time)
myvalues <- c(2001,2002,2003)
for (i in 1:3) 
{ y[[i]]<- df[df$time=myvalues[[i]],}

I would like to create three dataframes y1, y2, y3 for years 2001, 2002 and 2003. Any suggestions how do using a for loop?

Parfait
  • 97,543
  • 17
  • 91
  • 116
user3570187
  • 1,693
  • 1
  • 17
  • 30

1 Answers1

9

The assign() function is made for this. See ?assign() for syntax.

a <- c(1,2,3,4)
b <- c("kk","km","ll","k3")
time <- c(2001,2001,2002,2003)
df <- data.frame(a,b,time)
myvalues <- c(2001,2002,2003)

for (i in 1:3) {
  assign(paste0("y",i), df[df$time==myvalues[i],])
  }

See here for more ways to achieve this.

psychOle
  • 1,020
  • 9
  • 16