Replace values in r using case_when

Viewed 1728

I'm trying to replicate some Stata code in r. In my df, there is a variable "time" and one "exposure" (both numeric, so with values like 1,2,3 etc.

This is what the original Stata code looks like:

replace time = (time - 31) if exposure == 0

And this is what I tried:

recoded_df <- recoded_df %>% mutate(time = case_when(exposure == 0 ~ (time - 31))

I get the error that there is an "unexpected symbol" in the code. But I have no idea what I am doing wrong.

4 Answers
library(dplyr)

df <- data.frame(
  exposure = c(0, 1),
  time = c(81, 20)
)

df %>%
  mutate(
    time = case_when(exposure == 0 ~ time - 30,
                     TRUE ~ time)
  )

  exposure time
1        0   51
2        1   20

Using data.table, fifelse

library(data.table)
setDT(df)[, time := fifelse(!exposure, time - 30,  time)]

If I understand correctly, ifelse from base R should cover this:

recoded_df$time = ifelse(recoded_df$exposure == 0,
                         recoded_df$time - 31, recoded_df$time)

Here are two possibilities how you can achieve your task with a fake dataframe:

# fake dataframe:
df <- tribble(
  ~time, ~exposure,
  100, 0,
 70, 1, 
  90, 0, 
  60, 1, 
  50, 0
)

# 1. with mutate and ifelse
library(dplyr)
df %>% 
  mutate(time = ifelse(exposure == 0, time-31, time))

# 2. with base R and ifelse
df$time <- ifelse(df$exposure == 0, df$time - 31, df$time) 
Related