I am trying to apply some new conditions to the existing data frame (as below). I could not use ifelse
because the logic is like this:
- If count<=3: keep as it is
- If count>3 :
- If Code != "OFF15", c = "OK10" else c = "OFF15"
- If count > 3 and code is NA: Code= "OK10"
I could not generate the third condition when using ifelse
Code = c("OFF15","OFF5",NA,"OFF5",NA)
count= c(3,4,4,2,1)
x= data.frame(Code,count)
I could not use ifelse as there is nested list for that. My expected will be:
Code Count
OFF15 3
OK10 2
OK10 3
OFF5 2
NA 1
CodePudding user response:
You could use dplyr
:
library(dplyr)
df %>%
mutate(Code = case_when(count < 3 ~ Code,
count > 3 & Code != "OFF15" ~ "OK10",
TRUE ~ "OFF15"))
This returns
Code count
1 OFF15 3
2 OK10 4
3 OFF15 3
4 OFF5 2
5 <NA> 1
Note: I named the data.frame df
instead of x
.
CodePudding user response:
We can use nested ifelse
s (it is still borderline OK with just one level of nesting, otherwise case_when
is almost imperative).
library(dplyr)
df %>% mutate(Code = ifelse(count<=3, Code, ifelse(!Code %in% "OFF15", "OK10", "OFF15"))