'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?
Solution 1:[1]
This code worked for me:
df[df=="-95"]<-NA
Solution 2:[2]
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)))
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | TylerH |
Solution 2 | TylerH |