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?
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.
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.
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.
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.
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))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With