r - 如何在 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 但似乎无法得到答案。
解决方案
如果您只是想获得计数,那很简单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 日创建
推荐阅读
- c# - TinyMce 5.0.14 在 IE 和 Edge 上拼写检查错误不起作用
- python - 静态方法如何不绑定到“静态方法”类?
- javascript - InStr 与 indexOf
- visual-studio-code - 禁用自动替换 Visual Studio 代码
- c - 如何在 EOF 之前读取多个整数和字符串输入的 scanf?
- r - purrr::lift_vd 不适用于某些功能
- javascript - 当 body 使用 Fullpage.js 有一个类时隐藏或显示元素
- powershell - 如何将包含美元符号的参数传递给 Powershell 中的程序?/ 远程连接问题
- c++ - 对表进行排序 C++
- python - 如何使用 unicode 版本的 Windows API:mciSendString()、Python