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?

8
  • 3
    You have three problems - you need to initialize the list before the loop, y = list(), use == not = for testing equality, and you have unmatched brackets in your loop, {y[[i]] <- df[df$time == myvalues[i],]}. However instead of the for loop you can just do y = split(df, df$time) Commented Jun 15, 2017 at 19:11
  • 1
    See also how to make a list of data frames (possible dupe?). Commented Jun 15, 2017 at 19:12
  • @Gregor I would say so Commented Jun 15, 2017 at 19:29
  • He says he wants 3 dataframes. Not a list of 3 dataframes. Commented Jun 15, 2017 at 19:38
  • 2
    ok, so list2env(split(df, df$time), .GlobalEnv) Commented Jun 15, 2017 at 19:40

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.