首页 > 解决方案 > 从行中选择值以用于计算

问题描述

我正在尝试从列具有特定值的行中选择值,以便可以在计算中使用它。我曾尝试使用 dput 但它似乎不起作用 - 至少使用 stackoverflow 上的说明来生成可重现的示例。

 total.history <-           sum(recommendation$Spent[recommendation$Account=="History"])
$ Account: chr  "Art" "Biology" "Botany" "Languages" ...
     $ Product: chr  "Humanities" "Science" "Science" "Humanities" ...
     $ Region : chr  "Art" "Biology" "Botany" "Languages" ...
     $ Revenue: int  2000 75 1000 1000 200 200 5000 100 100 200
     $ Spent  : int  1000 30 444 234 100 123 250 56 23 156
     $ Left   : int  1000 45 556 766 100 77 4750 44 77 44

标签: r

解决方案


我们可以做的

with(recommendation, sum(Revenue[Account == "Biology"]))
#[1] 75

如果有多个元素,请使用%in%(或|与另一个表达式一起添加)

with(recommendation, sum(Revenue[Account %in% c("Biology", "Botany")]))
#[1] 1075

推荐阅读