简体   繁体   中英

How to modify a list of data.frame and then output the data.frame

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM