如何根据一个唯一键赋值但评估两行?
How to assign value based on one unique key but evaluating two rows?
如果对于每个唯一 id
,两个值列之一读取 0
那么我希望状态为 single
如果不是 mixed
。关于如何实现这一点有什么想法吗?
我不想要一个传播和聚集的解决方案。我不知道在 dplyr
中该怎么做
set.seed(111)
id <- c(1,1,2,2,3,3,4,4)
level <- c("high","low","high","low","high","low","high","low")
val <- c(9,0,2,4,1,0,0,2)
df <- data.frame(level, val,id)
df$level <- as.factor(as.character(df$level))
level val id status
1 high 9 1 single
2 low 0 1 single
3 high 2 2 mixed
4 low 4 2 mixed
5 high 1 3 single
6 low 0 3 single
7 high 0 4 single
8 low 2 4 single
这是一种方法。
library(dplyr)
df %>%
group_by(id) %>%
mutate(status = ifelse(any(val == 0), 'single', 'mixed')) %>%
ungroup()
#> # A tibble: 8 × 4
#> level val id status
#> <fct> <dbl> <dbl> <chr>
#> 1 high 9 1 single
#> 2 low 0 1 single
#> 3 high 2 2 mixed
#> 4 low 4 2 mixed
#> 5 high 1 3 single
#> 6 low 0 3 single
#> 7 high 0 4 single
#> 8 low 2 4 single
case_when
选项:
library(dplyr)
df %>%
group_by(id) %>%
mutate(status = case_when(any(val == 0) ~ "single",
TRUE ~ "mixed")) %>%
ungroup()
输出:
# A tibble: 8 × 4
level val id status
<fct> <dbl> <dbl> <chr>
1 high 9 1 single
2 low 0 1 single
3 high 2 2 mixed
4 low 4 2 mixed
5 high 1 3 single
6 low 0 3 single
7 high 0 4 single
8 low 2 4 single
如果对于每个唯一 id
,两个值列之一读取 0
那么我希望状态为 single
如果不是 mixed
。关于如何实现这一点有什么想法吗?
我不想要一个传播和聚集的解决方案。我不知道在 dplyr
中该怎么做set.seed(111)
id <- c(1,1,2,2,3,3,4,4)
level <- c("high","low","high","low","high","low","high","low")
val <- c(9,0,2,4,1,0,0,2)
df <- data.frame(level, val,id)
df$level <- as.factor(as.character(df$level))
level val id status
1 high 9 1 single
2 low 0 1 single
3 high 2 2 mixed
4 low 4 2 mixed
5 high 1 3 single
6 low 0 3 single
7 high 0 4 single
8 low 2 4 single
这是一种方法。
library(dplyr)
df %>%
group_by(id) %>%
mutate(status = ifelse(any(val == 0), 'single', 'mixed')) %>%
ungroup()
#> # A tibble: 8 × 4
#> level val id status
#> <fct> <dbl> <dbl> <chr>
#> 1 high 9 1 single
#> 2 low 0 1 single
#> 3 high 2 2 mixed
#> 4 low 4 2 mixed
#> 5 high 1 3 single
#> 6 low 0 3 single
#> 7 high 0 4 single
#> 8 low 2 4 single
case_when
选项:
library(dplyr)
df %>%
group_by(id) %>%
mutate(status = case_when(any(val == 0) ~ "single",
TRUE ~ "mixed")) %>%
ungroup()
输出:
# A tibble: 8 × 4
level val id status
<fct> <dbl> <dbl> <chr>
1 high 9 1 single
2 low 0 1 single
3 high 2 2 mixed
4 low 4 2 mixed
5 high 1 3 single
6 low 0 3 single
7 high 0 4 single
8 low 2 4 single