3

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
  • 87,576
  • 16
  • 87
  • 105
user3570187
  • 1,525
  • 1
  • 15
  • 29

1 Answers1

7

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
  • 960
  • 7
  • 15