I have an easy question. I want to mutate a new column as shown below.
DF<-data.frame(id=c(1,1,2,3,3),code=c("1","0","1","0","0"))
> DF
id code
1 1 1
2 1 0
3 2 1
4 3 0
5 3 0
Desired output:
id code type
1 1 1 mix
2 1 0 mix
3 2 1 A
4 3 0 B
5 3 0 B
Anyone eager to help?
CodePudding user response:
Maybe setting up conditions in case_when
is what you are looking for.
library(dplyr)
DF %>%
group_by(id) %>%
mutate(type = case_when(n_distinct(code) > 1 ~ 'mix',
all(code == 1) ~ 'A',
all(code == 0) ~ 'B')) %>%
ungroup
# id code type
# <dbl> <chr> <chr>
#1 1 1 mix
#2 1 0 mix
#3 2 1 A
#4 3 0 B
#5 3 0 B
CodePudding user response:
tidyverse
library(tidyverse)
df<-data.frame(id=c(1,1,2,3,3),code=c("1","0","1","0","0"))
df %>%
group_by(id) %>%
mutate(type = if_else(
n_distinct(code) > 1,
true = 99999,
false = as.numeric(cur_group_id())
)) %>%
ungroup() %>%
mutate(type = if_else(type == 99999, true = "mix", false = LETTERS[type - min(type) 1]))
#> # A tibble: 5 x 3
#> id code type
#> <dbl> <chr> <chr>
#> 1 1 1 mix
#> 2 1 0 mix
#> 3 2 1 A
#> 4 3 0 B
#> 5 3 0 B
Created on 2021-09-29 by the reprex package (v2.0.1)
data.table
library(data.table)
library(magrittr)
df<-data.frame(id=c(1,1,2,3,3),code=c("1","0","1","0","0"))
setDT(df)[, type := fifelse(test = uniqueN(code) > 1, yes = 99999, no = .GRP - 1), by = id] %>%
.[, type := fifelse(test = type == 99999, yes = "mix", no = LETTERS[as.numeric(type)])] %>%
.[]
#> id code type
#> 1: 1 1 mix
#> 2: 1 0 mix
#> 3: 2 1 A
#> 4: 3 0 B
#> 5: 3 0 B
Created on 2021-09-29 by the reprex package (v2.0.1)