问题
Suppose I have the following data frames in a list:
df1 <- data.frame(x = runif(3), y = runif(3))
df2 <- data.frame(x = runif(3), y = runif(3))
df.list <- list(df1, df2)
Now suppose I want to add column x and y to get column z I know to do this in a dataframe with mutate is as easy as:
dplyr::mutate(lapply(df.list, z = x + y))
How do I perform operations on multiple columns in a list using lapply?
回答1:
We can use transform
with lapply
lapply(df.list, transform, z= x+y)
If we need to do this for multiple columns,
lapply(df.list, transform, z= x+y, w= x*y)
Another option would be using library(purr)
(from the authors of dplyr
)
library(dplyr)
library(purrr)
df.list %>%
map(mutate, z=x+y, w= z*y)
来源:https://stackoverflow.com/questions/34797821/performing-an-operation-on-multiple-columns-in-a-list-of-data