我有一个包含许多列的 R 数据框,我只想对名为“Matt”的行下单元格值 >25 的列(标题:分数)求和。总和值可以放在最后一列之后。
input (df1)
Run Code Online (Sandbox Code Playgroud)
| 姓名 | 分数 | 分数 | 分数 | 分数 | 分数 |
|---|---|---|---|---|---|
| 亚历克斯 | 31 | 15 | 18 | 22 | 23 |
| 拍 | 37 | 18 | 29 | 15 | 28 |
| 马特 | 33 | 27 | 18 | 88 | 9 |
| 詹姆士 | 12 | 36 | 32 | 13 | 21 |
output (df2)
Run Code Online (Sandbox Code Playgroud)
| 姓名 | 分数 | 分数 | 分数 | 分数 | 分数 | 马特 |
|---|---|---|---|---|---|---|
| 亚历克斯 | 31 | 15 | 18 | 22 | 23 | 68 |
| 拍 | 37 | 18 | 59 | 55 | 28 | 110 |
| 马特 | 33 | 27 | 18 | 88 | 9 | 148 |
| 詹姆士 | 12 | 36 | 32 | 13 | 21 | 61 |
任何想法都非常受欢迎,
问候,
一个选择是提取'Name'为'Matt'的行,没有第一列创建一个逻辑向量('i1'),用它来对列进行子集化并得到 rowSums
i1 <- df1[df1$Name == "Matt",-1] > 25
df1$Matt <- rowSums(df1[-1][,i1], na.rm = TRUE)
Run Code Online (Sandbox Code Playgroud)
或使用 tidyverse
library(dplyr)
df1 %>%
mutate(Matt = rowSums(select(cur_data(),
where(~ is.numeric(.) && .[Name == 'Matt'] > 25))))
Run Code Online (Sandbox Code Playgroud)
-输出
# Name score score.1 score.2 score.3 score.4 Matt
#1 Alex 31 15 18 22 23 68
#2 Pat 37 18 29 15 28 70
#3 Matt 33 27 18 88 9 148
#4 James 12 36 32 13 21 61
Run Code Online (Sandbox Code Playgroud)
df1 <- structure(list(Name = c("Alex", "Pat", "Matt", "James"), score = c(31L,
37L, 33L, 12L), score.1 = c(15L, 18L, 27L, 36L), score.2 = c(18L,
29L, 18L, 32L), score.3 = c(22L, 15L, 88L, 13L), score.4 = c(23L,
28L, 9L, 21L)), class = "data.frame", row.names = c(NA, -4L))
Run Code Online (Sandbox Code Playgroud)