I have a data frame df with 2 columns one of them income the other one level, level it’s ok, it’s categorical, but income is numerical, I want to recode it to categorical as well, for example if income < 130000 then using the name income = "Less than 130000" , if income < 500000 but >=130000 then using the name income = "Between 130000 and 500000" finally if income > 500000 but <= 2000000 then using the name income = "Between 5000000 and 20000000"
df %>% mutate_at(vars(one_of(df$income)),
function(x) case_when(
x < 130000 ~ "less than 130000",
x <500000 ~ "between 130000 and 500000",
x <=20000000 ~ "between 500000 and 2000000"
))
But it doesn’t work, any help it’s appreciated.
This is head(df) please read ingresoph as income
>Solution :
Please look below, we can remove the need for the function(x) along with the _at
df %>% mutate(income =
case_when(
income < 130000 ~ "less than 130000",
income <500000 ~ "between 130000 and 500000",
income <=20000000 ~ "between 500000 and 2000000",
T ~ as.character(NA)
))
Basically only use mutate_at if there is a specific reason to (i.e. I want to pull all numeric columns, or all character columns, etc.)
Also, if you attempt to do NA for any other outside values, make sure to wrap it in a as.character() as your mutate will throw an error due to different datatypes (logical and character).