首页 > 解决方案 > 如何在 R 中逐行汇总包含某个值的单元格的数量?

问题描述

我的数据如下

 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 但似乎无法得到答案。

标签: r

解决方案


如果您只是想获得计数,那很简单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 包(v0.2.1)于 2019 年 12 月 14 日创建


推荐阅读