Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sum all values in every column of a data.frame in R

Tags:

r

Given this data set:

  Name Height Weight 1 Mary     65    110 2 John     70    200 3 Jane     64    115 

I'd like to sum every qualifier columns (Height and Weight) yielding

 199  425 

The problem is that the qualifiers can be more than just 2 (i.e. more than just Height and Weight).

I can do this.

    # Create the dataframe people     Name <- c("Mary", "John", "Jane")     Height <- c(65,70,64)     Weight <- c(110,200,115)     people <- data.frame(Name, Height, Weight)      res <- c(sum(people$Height),sum(people$Weight)) 

But it gets too long when the qualifier increase. What's the compact way to do it?

like image 431
pdubois Avatar asked Aug 23 '13 06:08

pdubois


People also ask

How do I sum everything in a column in R?

Sum Function in R – sum() sum of a particular column of a dataframe. sum of a group can also calculated using sum() function in R by providing it inside the aggregate function. with sum() function we can also perform row wise sum using dplyr package and also column wise sum lets see an example of each.

How do you find the sum of all N values in R data frame columns?

To find the sum of every n values in R data frame columns, we can use rowsum function along with rep function that will repeat the sum for rows.

How do I sum an array of columns in R?

To find the sum of row, columns, and total in a matrix can be simply done by using the functions rowSums, colSums, and sum respectively.

How do I summarize a Dataframe in R?

R – Summary of Data Frame To get the summary of Data Frame, call summary() function and pass the Data Frame as argument to the function. We may pass additional arguments to summary() that affects the summary output. The output of summary() contains summary for each column.


1 Answers

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)) 
like image 156
Didzis Elferts Avatar answered Sep 23 '22 12:09

Didzis Elferts