Semyon Tamara Semyon Tamara - 1 month ago 5
R Question

How to get sum of observations of a variable using sapply/lapply for a list of data frames?

I want to get the sum of values for a variable in each data frame in a list. I have something similar to this:

l <- list(a = mtcars, b = mtcars, c = mtcars)
v <- sapply(l, function(x)sum(l$x$disp))


I expect to get a named vector containing sums. Instead I get only zeros. My guess would be that only name of the data frame is passed to the function.

I tried other functions and lapply but every time I get a list/vector with Nulls or zeros. It is possible to use for statement for this task, but in my case I have list containing lists of data frames and nested loops in R seem not to be a good choice.
Do you have any ideas what I am missing?
Thanks in advance.

Answer

I think you need,

sapply(l, function(x) sum(x["disp"]))

#  a      b      c 
#7383.1 7383.1 7383.1 

Or if you need the complete sum of disp variable across all the list, you can wrap it completely in sum

sum(sapply(l, function(x) sum(x["disp"])))

#[1] 22149.3
Comments