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
source to share
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(`+`)
source to share