1

I am trying to add a new column to multiple data frames, and then replace the original data frame with the new one. This is how I am creating the new data frames:

df1 <- data.frame(X1=c(1,2,3),X2=c(1,2,3))
df2 <- data.frame(X1=c(4,5,6),X2=c(4,5,6))

groups <- list(df1,df2)
groups <- lapply(groups,function(x) cbind(x,X3=x[,1]+x[,2]))
groups

[[1]]
  X1 X2 X3
1  1  1  2
2  2  2  4
3  3  3  6

[[2]]
  X1 X2 X3
1  4  4  8
2  5  5 10
3  6  6 12

I'm satisfied with how the new data frames have been created. What I'm stuck on is then breaking up my groups list and then saving the list elements back into their respective original data frames.

Desired Output

Essentially, I want to do something like df1,df2 <- groups[[1]],groups[[2]] but that is of course not syntatically valid. I have more than 2 data frames, which is why I'm hoping for a more programmatic approach than simply typing out N lines of code.

ZachTurn
  • 636
  • 1
  • 5
  • 14
  • 2
    Keeping data.frames with the same structure in lists is usually a pretty good idea in R as you can use `lapply` and other tools to work with them. See gregor's answer on [this question](http://stackoverflow.com/questions/17499013/how-do-i-make-a-list-of-data-frames) for a number of useful tips. You can also add names to your list item to make them easier to access: `names(groups) <- c("df1", "df2")`. – lmo Jun 17 '16 at 18:48
  • Thank you, that's a very informative thread. I'll try to implement that approach. I am still curious about my original question, if anyone would still care to answer. – ZachTurn Jun 17 '16 at 19:00

2 Answers2

3
for (i in 1:length(groups)){
   assign(paste("df",i,sep=""),as.data.frame(groups[[i]]))
}

should do it. Try it out, please.

Rockbar
  • 1,081
  • 1
  • 20
  • 31
  • Close. It should be `for (i in 1:length(groups)){ assign(paste0("df",i),as.data.frame(groups[[i]])) }` – Gaius Augustus Jun 17 '16 at 19:36
  • Thank you, your post was helpful in guiding me to my own answer. Your solution works when the data frames are sequentially numbered, but I will post an answer that will work for any naming conventions. – ZachTurn Jun 17 '16 at 20:06
1

@Rockbar led me to a general solution as well:

for(i in 1:length(groups)){
  assign(names(groups)[i],as.data.frame(groups[[i]]))
}

> df1
  X1 X2 X3
1  1  1  2
2  2  2  4
3  3  3  6
> df2
  x1 X3 X3
1  4  4  8
2  5  5 10
3  6  6 12

I should note that this only works if the objects in the list are all named. Thank you again @Rockbar for guiding me to this.

ZachTurn
  • 636
  • 1
  • 5
  • 14