5

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)
josliber
  • 43,891
  • 12
  • 98
  • 133
bill999
  • 2,147
  • 8
  • 51
  • 103
  • 3
    You have to return the data frame: `lapply(l, function(x) { x[,2]*2 -> x$new; x })`. – lukeA Mar 02 '15 at 22:20
  • @lukeA Could you please clarify the syntax of what is in the { }'s? – bill999 Mar 02 '15 at 22:35
  • 1
    The only thing, which is different from yours, is `return(x)` - or short: `x`. As the function contains not only one command, but two (seperated by `;` or by a linefeed), you got to wrap it in `{`...`}`. `x` returns the data frame after you added `new `to it. – lukeA Mar 02 '15 at 22:37
  • Got it! Now I can just assign it back to `l` and be good. Thanks! – bill999 Mar 02 '15 at 22:39

1 Answers1

4

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
josliber
  • 43,891
  • 12
  • 98
  • 133