jormaga
jormaga

Reputation: 311

Apply function to column of data frame (column is a list)

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!

Upvotes: 2

Views: 12259

Answers (2)

Cettt
Cettt

Reputation: 11981

the following works for your example

sapply(df[,2], function(x) sum(x)+2)

Upvotes: 6

akrun
akrun

Reputation: 886948

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)

Upvotes: 4

Related Questions