如何将新值从lapply分配给列表中数据框的新列 [英] How to assign new values from lapply to new column in dataframes in list
本文介绍了如何将新值从lapply分配给列表中数据框的新列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个数据框列表。我想对数据框的列执行操作,然后在数据框中使用生成的新列创建新列。
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)
我想要的是 4 6 8
和 10 12 4
分别分配给第一和第二个数据帧的第三列。
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.
这似乎不起作用:
lapply(l, function(x) x[,2]*2 -> x$new)
推荐答案
您可以使用 cbind
添加新列到列表中的数据帧:
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
这篇关于如何将新值从lapply分配给列表中数据框的新列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文