How to assign new values from lapply to new column in dataframes in list

点点圈 提交于 2019-12-11 00:05:10

问题


I have a list of dataframes. I want to perform an operation on columns of the dataframes and then create a new column in the dataframes with the resulting new column.

a <- data.frame(c(1,2,3), c(2,3,4))
b <- data.frame(c(7,8,9), c(5,6,2))
l <- list(a, b)
lapply(l, function(x) x[,2]*2)

What I want is for 4 6 8 and 10 12 4 to be assigned to the third columns of the first and second dataframes, respectively.

This does not seem to work:

lapply(l, function(x) x[,2]*2 -> x$new)

回答1:


You can use cbind to add the new column to the data frames in the list:

lapply(l, function(x) cbind(x, x[,2]*2))
# [[1]]
#   c.1..2..3. c.2..3..4. x[, 2] * 2
# 1          1          2          4
# 2          2          3          6
# 3          3          4          8
# 
# [[2]]
#   c.7..8..9. c.5..6..2. x[, 2] * 2
# 1          7          5         10
# 2          8          6         12
# 3          9          2          4


来源:https://stackoverflow.com/questions/28820505/how-to-assign-new-values-from-lapply-to-new-column-in-dataframes-in-list

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