简体   繁体   English

使用 case_when 替换 r 中的值

[英]Replace values in r using case_when

I'm trying to replicate some Stata code in r.我正在尝试在 r 中复制一些 Stata 代码。 In my df, there is a variable "time" and one "exposure" (both numeric, so with values like 1,2,3 etc.在我的 df 中,有一个变量“时间”和一个“曝光”(均为数字,因此具有 1、2、3 等值)。

This is what the original Stata code looks like:这是原始Stata代码的样子:

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.但我不知道我做错了什么。

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使用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:如果我理解正确,来自基础ifelse的 ifelse 应该涵盖以下内容:

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:以下是使用假 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) 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM