我将数据组织到类中,如果所有的scores1值都在100以上,那么我希望它们的true_score为scores1。然而,如果班里有人的score1值低于100,那么我想把他们的scorel和score2值相加,作为他们的真实分数。
我已经尝试过并想使用dplyr的if_all((,但我无法使用它。
这是我的模拟数据:
library(tidyverse)
test <- tibble(person = c("c", "s", "j"),
class = c(1, 2, 2),
score1 = c(101, 200, 23),
score2 = c(200, 100, 25))
这是我想要的:
answer <- tibble(person = c("c", "s", "j"),
class = c(1, 2, 2),
score1 = c(101, 200, 23),
score2 = c(200, 100, 25),
true_score = c(101, 300, 48))
这是我(失败的(尝试:
test %>%
group_by(class) %>%
mutate(true_score = case_when(
if_all(score1 > 100), score1 > 100 ~ score1,
score1 + score2 > 100 ~ score1 + score2
))
Error in `mutate()`:
! Problem while computing `true_score = case_when(...)`.
ℹ The error occurred in group 1: class = 1.
Caused by error in `if_all()`:
! object 'score1' not found
if_all()
(和if_any()
(用于跨列而非内部。在这种情况下,您需要普通的旧all()
:
library(dplyr)
test %>%
group_by(class) %>%
mutate(true_score = case_when(all(score1 > 100) ~ score1,
TRUE ~ score1 + score2)) %>%
ungroup()
# A tibble: 3 × 5
person class score1 score2 true_score
<chr> <dbl> <dbl> <dbl> <dbl>
1 c 1 101 200 101
2 s 2 200 100 300
3 j 2 23 25 48