i'm trying to transform variable with mutation function. I'm using mutate with case_when statement.
The example is as follows. The data is about customer's preference(pref
). In case of pref
is 1 and 5, I will transform it to 'extreme', in case of 2 and 4, it will be 'modest', else(pref
==3), it will be 'none'.
set.seed(9999)
pref<-sample(x=1:5,size=10,replace=TRUE)
df<-data.frame(pref)
df
pref
1 5
2 1
3 1
4 4
5 3
6 5
7 5
8 1
9 5
10 1
I use the statement as follows. However, the NA appeared. It might seem that case_when only recognize the logical statement, not vector. However, using logical vector, the code become a little bit messy(The original data scale is broader than 5 scale, and condition is more complex.) How can I solve this problem?
I would appreciate all your help.
df<-df%>%mutate(prefcat=case_when(pref==c(1,5)~"extreme",
pref==c(2,4)~"modest",
pref==c(3)~"none"))
df
pref prefcat
1 5 <NA>
2 1 <NA>
3 1 extreme
4 4 modest
5 3 none
6 5 extreme
7 5 <NA>
8 1 <NA>
9 5 <NA>
10 1 <NA>