Apply function to column of data frame (column is a list)
11,772
Solution 1
the following works for your example
sapply(df[,2], function(x) sum(x)+2)
Solution 2
We can use sapply
df$NewCol <- sapply(df$X2, function(x) sum(x) + 2)
Or using the OP's function, but unlist
is not needed
sapply(df$X2, sum2)
Author by
jormaga
Updated on June 05, 2022Comments
-
jormaga almost 2 years
I have a data frame with 2 columns, the first is the ID number and the second one is a list of numbers. I have defined a function which sums up the list and add 2. What I'd like to do is to do the calculation for all rows without using a for loop. I tried using apply but I can't make it work...
Here's the code:
The test data frame:
d1 <- c(1,2,3,4,5) d2 <- c(4,6,8) d3 <- c(5,10) df1 <- data.frame(cbind(1, I(list(d1)))) df2 <- data.frame(cbind(2, I(list(d2)))) df3 <- data.frame(cbind(3, I(list(d3)))) df <- rbind(df1, df2, df3)
The defined function sum2:
sum2 <- function(a) { sum(unlist(a)) + 2 }
How can I use apply and add a third column to df containing the calculated value?
Thanks!