Sum items in list data.frames

I have a list (Total) of 12 data.frames (all the same forms) and I need the sum of each row of the list in colum 2.

I'm looking for a smarter way to sum the items in a list like this:

Total[[1]][,2] + Total[[2]][,2] + Total[[3]][,2] +..+Total[[12]][,2]

      

colum 2 is 70 in length, so the result should be a vector of length 70

hope someone knows he is right sapply

, lapply

or apply

functional code

+3


source to share


2 answers


There is an option here:

Reduce("+", lapply(Total, "[[", 2))

      

Note, however, that this does not work well with potential NA due to +

.



Here's an example with inline data:

Reduce("+", lapply(list(iris, iris, iris), "[[", 2))

      

+11


source


We can use rowSums

after extracting the second column from list

of data.frame

. In case of any missing values, na.rm=TRUE

take care of this.

rowSums(sapply(Total, `[[`, 2), na.rm = TRUE)

      




Or another option tidyverse

library(tidyverse)
Total %>%
      map(~.[[2]]) %>% 
      #or as suggested in the comments
      #map(2) %>%
      reduce(`+`)

      

+6


source







All Articles