How to sum all values of a column of in a data.frame?
I have a data frame with several columns; some numeric and some character. How to compute the sum of a specific column? I’ve googled for this and I see numerous functions (sum, cumsum, rowsum, rowSums, colSums, aggregate, apply) but I can’t make sense of it all.
For example, suppose I have a data frame people with the following columns
Name Height Weight
Mary 65 110
John 70 200
Jane 64 115
…
How do I get the sum of all the weights?
To solve how to sum a column in r you should put all values in a column of a data frame then use the sum() function from the base package as follows:
sum(people$Weight, na.rm = TRUE)
#na.rm = TRUE will remove all 'NA' values in the column
For example:
df <- data.frame(p=c(10,8,7,3,2,6,7,8),
v=c(100,300,150,400,450,250,150,400))
> df
p v
1 10 100
2 8 300
3 7 150
4 3 400
5 2 450
6 6 250
7 7 150
8 8 400
sum(df$p, na.rm = TRUE)
[1] 51
Note - you can get built-in help by using ?sum, ?colSums, etc. (by the way, colSums will give you the sum for each column).