Dplyr filter with condition

Viewed 51

I have this df

ID CODE
A  45676
B  87898
B  89998
A  45688
A  45556

I would like to get this df

ID CODE    CODE_SUB
A  45676   76
B  87898   NA
B  89998   NA
A  45688   88
A  45556   56

CODE_SUB is last two characters from CODE with condition ID == A

I used this code

mutate(CODE_SUB = substr(which (df$ID == "A"), CODE , start= 4, stop= 5))

But

Error: Problem with mutate() input CODE_SUB. x unused argument (CODE)

2 Answers

One base R solution could be:

with(df, (ID == "A")^NA * as.numeric(substr(CODE, nchar(CODE)-1, nchar(CODE))))

[1] 76 NA NA 88 56

You can use the ifelse function inside mutate

df %>% mutate(CODE_SUB = as.numeric(ifelse(ID == "A", substr(CODE, start = 4, stop = 5), NA)))

Output

#   ID  CODE CODE_SUB
# 1  A 45676       76
# 2  B 87898       NA
# 3  B 89998       NA
# 4  A 45688       88
# 5  A 45556       56
Related