问题
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