如何对 data.frame 列值求和? [英] How to sum data.frame column values?
问题描述
我有一个包含几列的数据框;一些数字和一些字符.如何计算特定列的总和?我已经为此搜索过很多函数(sum
、cumsum
、rowsum
, rowSums
, colSums
, aggregate
, apply
) 但我无法理解这一切.
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.
例如,假设我有一个数据框 people
包含以下列
For example suppose I have a data frame people
with the following columns
people <- read(
text =
"Name Height Weight
Mary 65 110
John 70 200
Jane 64 115",
header = TRUE
)
…
如何获得所有权重的总和?
How do I get the sum of all the weights?
推荐答案
你可以使用 sum(people$Weight)
.
sum
对向量求和,people$Weight
从您的数据框中检索权重列.
sum
sums up a vector, and people$Weight
retrieves the weight column from your data frame.
注意 - 您可以通过使用 ?sum
、?colSums
等获得内置帮助(顺便说一下,colSums
将给你每列的总和).
Note - you can get built-in help by using ?sum
, ?colSums
, etc. (by the way, colSums
will give you the sum for each column).
这篇关于如何对 data.frame 列值求和?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!