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

R – Replace all NA's in a dataframe with NULL

How can I replace all ‘NA‘ with ‘NULL‘ in an R dataframe without specifying column names?
I found replace_na function from tidyr which has an example as:

# Replace NAs in a data frame
df <- tibble(x = c(1, 2, NA), y = c("a", NA, "b"))
df %>% replace_na(list(x = 0, y = "unknown")) 

but my table has more than 10 columns and it could change. Can’t specify column names like in the example above.

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 :

Base R way to do this:

apply(df, 2, function(x) { x[ is.na(x) ] <- 'NULL'; x})

Note that you can’t really insert NULL as it has length 0, you can insert: '' or 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