You need to enable JavaScript to run this app. RStudio中基于period列数值创建新列intervention的问题咨询
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.21 09:15:02