Doug Fir
Doug Fir

Reputation: 21302

Replace a string across entire dataframe

I have a data frame with many features and I know from ad hoc checking that many of them contain the value "NULL" which I would like to replace with NA.

I know that I can use str_replace column by column, my question is, is there a short hand e.g.

mydf <- mydf %>% str_replace_all("NULL", NA)

For example:

example_mtcars <- mtcars %>% mutate_at(vars(disp, wt, qsec), funs(as.character(.)))
example_mtcars$disp[c(2,4,8)] <- "NULL"
example_mtcars$wt[c(10, 12)] <- "NULL"
example_mtcars$qsec[c(2,3,4)] <- "NULL"

What is the shortest, least code way to replace all instances of "NULL" across the entire data frame example_mtcars?

Upvotes: 1

Views: 281

Answers (3)

Rui Barradas
Rui Barradas

Reputation: 76651

A one-liner with function is.na<-.

is.na(example_mtcars) <- example_mtcars == "NULL"

Upvotes: 0

Lorenzo M
Lorenzo M

Reputation: 96

Shree's solution is fine, but below is the general technique you'd want to use to apply a function to every column of your data frame.

mydf <-
    1:ncol(mydf) %>%
        map_df(function_to_apply_to_col())

Upvotes: 0

Shree
Shree

Reputation: 11150

Here's a way -

example_mtcars[example_mtcars == "NULL"] <- NA

Upvotes: 3

Related Questions