Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Recode a column in a data frame in R, base on < or > conditions

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
enter image description here

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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).

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading