Home > Blockchain >  Create a Vector with the Sums of a Specific Column of all Dataframes in a List
Create a Vector with the Sums of a Specific Column of all Dataframes in a List

Time:08-24

I have a list of dataframes:

df1 <- data.frame(c(1:10), c(11:20), c(31:40), c(1,2))
colnames(df1) <-c("a","b","c","d")

df2 <- data.frame(c(2:11), c(12:21), c(31:40), c(1,1))
colnames(df2) <-c("a","b","c","d")

df3 <- data.frame(c(1:12), c(11:22), c(31:42), c(2,2))
colnames(df3) <-c("a","b","c","d")

mylist <- list(df1,df2,df3)
names(mylist) <- c("ID_1", "ID_2", "ID_3")

I would like to obtain a vector with the sums of column d of all dataframes of that list. My solution is:

c(sum(mylist$ID_1$d), sum(mylist$ID_2$d), sum(mylist$ID_3$d))

This works but I'm looking for a more efficient way because I have a list with very many dataframes.

CodePudding user response:

Try either of the following:

sapply(mylist, function (x) sum(x$d))
unname( sapply(mylist, function (x) sum(x$d)) )
unlist( lapply(mylist, function (x) sum(x$d)), use.names = FALSE )
  • Related