RStudio中基于period列数值创建新列intervention的问题咨询
R 实现多条件生成新列的两种方案
方法1:基础R原生实现
# 构造初始数据框 df <- data.frame(period = c(-12, -11, -10, -9, -8, -7, -6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4,5, 6, 7, 8, 9, 10, 11)) # 按规则生成intervention列 df$intervention <- ifelse(df$period < 0, 0, ifelse(df$period > 0, df$period, ""))
方法2:dplyr 包实现(逻辑可读性更高)
library(dplyr) df <- df %>% mutate(intervention = case_when( period < 0 ~ 0, period > 0 ~ period, .default = "" ))
补充说明:由于要求period=0时返回空字符串(字符类型),生成的intervention列默认会转为字符类型。如果后续需要对该列做数值运算,可把代码中的""替换为NA_real_,即可保持列为数值类型,0值对应位置为数值缺失值,更方便后续处理。
内容的提问来源于stack exchange,提问作者Baz
相关产品推荐
相关产品推荐

