如何对数据。frame中的一列的所有值进行求和?

时间:2021-07-27 07:56:10

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.

我有一个数据框架,有几个列;一些数字和一些字符。如何计算某一列的和?我用谷歌搜索了一下,看到了很多函数(sum、cumsum、rowsum、rowsum、colsum、aggregate、apply),但我搞不懂。

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?

如何得到所有权重的和?

1 个解决方案

#1


63  

You can just use sum(people$Weight).

你可以用sum(人$Weight)。

sum sums up a vector, and people$Weight retrieves the weight column from your data frame.

sum汇总一个向量,people$Weight从您的数据帧中检索权重列。

Note - you can get built-in help by using ?sum, ?colSums, etc. (by the way, colSums will give you the sum for each column).

注:您可以通过使用?sum、? colsum等获得内置帮助(顺便说一下,colsum将为您提供每一列的总和)。

#1


63  

You can just use sum(people$Weight).

你可以用sum(人$Weight)。

sum sums up a vector, and people$Weight retrieves the weight column from your data frame.

sum汇总一个向量,people$Weight从您的数据帧中检索权重列。

Note - you can get built-in help by using ?sum, ?colSums, etc. (by the way, colSums will give you the sum for each column).

注:您可以通过使用?sum、? colsum等获得内置帮助(顺便说一下,colsum将为您提供每一列的总和)。