【问题标题】:How can I sum the number of cells containing a certain value by row in R? [duplicate]如何在 R 中逐行汇总包含某个值的单元格的数量? [复制]
【发布时间】:2019-12-14 19:26:01
【问题描述】:

我的数据如下

 Name  Maths  Science  English  History  German
 Alex  100    98       88       90       89
 Adam  90     100      98       98       98
 James 98     89       90       98       100
 Matt  98     80       100      99       99
 Pat   98     98       98       100      84

现在,我想逐行添加“98”分数的数量。我怎样才能做到这一点? 我尝试过使用 rowSums,但似乎无法得到答案。

【问题讨论】:

  • 试试apply(df[2:6],1,function(x)sum(x[as.numeric(trimws(x))==98]))

标签: r


【解决方案1】:

如果您只想获得计数,只需 rowSums(df == 98)

如果要将其添加为列,则在基础 R 中:

df[, "total"] <- rowSums(df == 98)
df
#>    Name Maths Science English History German total
#> 1  Alex   100      98      88      90     89     1
#> 2  Adam    90     100      98      98     98     3
#> 3 James    98      89      90      98    100     2
#> 4  Matt    98      80     100      99     99     1
#> 5   Pat    98      98      98     100     84     3

或者在dplyr,如果你愿意的话:

library(dplyr)

df %>% mutate(total = rowSums(. == 98))
#>    Name Maths Science English History German total
#> 1  Alex   100      98      88      90     89     1
#> 2  Adam    90     100      98      98     98     3
#> 3 James    98      89      90      98    100     2
#> 4  Matt    98      80     100      99     99     1
#> 5   Pat    98      98      98     100     84     3

这是数据:

txt <- " Name  Maths  Science  English  History  German
 Alex  100    98       88       90       89
 Adam  90     100      98       98       98
 James 98     89       90       98       100
 Matt  98     80       100      99       99
 Pat   98     98       98       100      84"

df <- read.table(text = txt, header = TRUE)

reprex package (v0.2.1) 于 2019 年 12 月 14 日创建

【讨论】:

  • 如果变量是字符而不是数字或整数,同样的代码会起作用吗?
  • 其实我以为没有,但是我刚刚测试了一下,好像还不错。如果您有问题,请使用您的一小部分数据样本的dput 编辑您的帖子,我会看一看。
猜你喜欢
  • 1970-01-01
  • 2015-11-06
  • 2019-06-01
  • 2022-01-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-01-13
相关资源
最近更新 更多