我將資料組織成類,如果所有 score1 值都高于 100,那么我希望它們的 true_score 為 score1。但是,如果班上任何人的 score1 值低于 100,那么我想將他們的 score1 和 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
uj5u.com熱心網友回復:
if_all()(and if_any()) 用于跨列而不是在列內使用。在這種情況下,您需要簡單的 old 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
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/517950.html
上一篇:使用列的分類值洗掉R中的索引
