0

I want to create a second column in each of a list of data.frames that is just a duplicate of the first column, and then output those data.frames:

store the data frames:

> FileList <- list(DF1, DF2)

Add another column to each data frame:

> ModifiedDataFrames <- lapply(1:length(FileList), function (x) {FileList[[x]]$Column2 == FileList[[x]]$Column1})

but ModifiedDataFrames[[1]] just returns a list which contains what I assume is the content from DF1$Column1

What am I missing here?

Sky Scraper
  • 148
  • 1
  • 10
  • Your function should return the updated data.frame. When you do an assignment, just the right hand term is returned, not the data.frame. You can add `return(FileList[[x]])` to your function. It's easier to help you if you include a simple [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input and desired output that can be used to test and verify possible solutions. – MrFlick Mar 02 '21 at 20:14
  • @MrFlick oh ok because you need to specify what sapply should return, otherwise it just return the standard out from the run of the function. so in this case it was just returning ``FileList[[x]]$Column1`` – Sky Scraper Mar 02 '21 at 21:33

1 Answers1

0

There are a few problems with your code. First, you are using the equivalence operator == for assignment and second you are not returning the correct element from your function. Here is a possible solution:

df1 <- data.frame(Column1 = c(1:3))  
df2 <- data.frame(Column1 = c(4:6))  
FileList <- list(df1, df2)
ModifiedDataFrames <- lapply(FileList, function(x) {
  x$Column2 <- x$Column1
  return(x)
})

> ModifiedDataFrames
[[1]]
  Column1 Column2
1       1       1
2       2       2
3       3       3

[[2]]
  Column1 Column2
1       4       4
2       5       5

GordonShumway
  • 1,980
  • 13
  • 19
  • yea, the equivalence operator wasn't going to work, I was just getting frustrated and was trying random things. specifying the return element was what I was missing. Thanks sorry. – Sky Scraper Mar 02 '21 at 21:35