Sum all values in every column of a data.frame in R
mapply(sum,people[,-1])
Height Weight
199 425
You can use function colSums()
to calculate sum of all values. [,-1]
ensures that first column with names of people is excluded.
colSums(people[,-1])
Height Weight
199 425
Assuming there could be multiple columns that are not numeric, or that your column order is not fixed, a more general approach would be:
colSums(Filter(is.numeric, people))
We can use dplyr
to select only numeric columns and purr
to get sum
for all columns. (can be used to get what ever value for all columns, such as mean, min, max, etc. )
library("dplyr")
library("purrr")
people %>%
select_if(is.numeric) %>%
map_dbl(sum)
Or another easy way by only using dplyr
- As of (dplyr 1.0.0) we can use across()
library("dplyr")
people %>%
summarise(across(where(is.numeric), ~ sum(.x, na.rm = TRUE)))
library("dplyr")
people %>%
summarize_if(is.numeric, sum, na.rm=TRUE)