Performing an operation on multiple columns in a list of data

倾然丶 夕夏残阳落幕 提交于 2019-12-11 11:48:39

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!