Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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 )
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading