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 continuous data into categorical data using is.na() and if_else() in R

I have a data frame and one of the columns contain both continuous data and NA. I want to recode all continuous data as one level of categorical data and the NA as another using if_else() and is.na(). How can I do it?

Example data frame:

df<-tibble(id=1:10,score=c(3,1,-3,-9,NA,NA,12,NA,5,NA))

How can I recode all the numbers into "results" and NA into "no_results"?

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 :

I have provided a toy example to stand in for the code that you described:

df <- data.frame(x = c(1,2,3,4,NA,NA,NA,NA))

Here, we have a data frame with continuous and NA values, and using dplyr, we can use you functions to categorize "x":

library(dplyr)
df <- df %>% 
mutate(new_data = if_else(is.na(x), "is NA", "is not NA"))

This creates a new column that categorizes your NA values to "is NA".

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