Lili
Lili

Reputation: 587

How to replace a value with NA across an entire dataframe

Is there any way to replace all the "-95" that can possibly exist in a dataframe with NA across all the columns?

Upvotes: 1

Views: 773

Answers (2)

Steffen Moritz
Steffen Moritz

Reputation: 7730

If you have more complicated cases, where you have multiple values that shall be converted into NAs, maybe according to some specific conditions, the naniar package can be quite helpful. There are the following functions:

naniar::replace_with_na()
naniar::replace_with_na_if()
naniar::replace_with_na_at()

These can be quite helpful and are quite powerful. Probably the best intro is looking at the documentation of these functions.

Here a small example, if you have a dataframe with a x and a z variable and for your x you want to have -99 and -98 encoded to NA, while for your z variable you want to have -99 and -97 to be encoded to NA.

library(naniar)
df %>%
  replace_with_na(replace = list(x = c(-99,-98),
                             z = c(-99, -97)))

Upvotes: 2

Lili
Lili

Reputation: 587

This code worked for me:

df[df=="-95"]<-NA

Upvotes: 0

Related Questions