I have a continuous variable. Entries 1-60 need to stay the same. NAs and 0s are coded as a number above 60.
Asked
Active
Viewed 101 times
4 Answers
2
With dplyr
, you can use
recode()
df %>%
mutate(y = recode(x, `88` = 0, `99` = NA_real_))
case_match()
df %>%
mutate(y = case_match(x, 88 ~ 0, 99 ~ NA, .default = x))
case_when()
df %>%
mutate(y = case_when(x == 88 ~ 0, x == 99 ~ NA, .default = x))

Darren Tsai
- 32,117
- 5
- 21
- 51
1
Using fcase
library(data.table)
setDT(df)[, y := fcase(!x %in% c(88, 99), x, x == 88, 0)]

akrun
- 874,273
- 37
- 540
- 662
0
You have a lot of options at your disposal with the tidyverse
packages (e.g., dplyr
, tidyr
). One option is to use na_if
to turn the 99s into NA
and if_else
to turn the 88s to 0.
I have created a fake dataset below, but if you have questions about your specific dataset, you should provide a reproducible example with your own data.
library(tidyverse)
a <- sample(x = c(1, 2, 3, 4, 99, 88), size = 30, replace = T)
b <- sample(x = c(1, 2, 3, 4, 99, 88), size = 30, replace = T)
c <- sample(x = c(1, 2, 3, 4, 99, 88), size = 30, replace = T)
df <- data.frame(a, b, c)
df
df %>%
mutate(across(everything(), ~na_if(., 99))) %>%
mutate(across(everything(), ~if_else(. == 88, 0, .)))

jrcalabrese
- 2,184
- 3
- 10
- 30
0
We can update matching values inplace with base R
df$y[df$y == 99] <- NA
df$y[df$y == 88] <- 0

GuedesBF
- 8,409
- 5
- 19
- 37