You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在R中为同时存在于2010和2012年的ID生成dummy variable

在R中创建判断id是否同时存在2010和2012年的哑变量

首先先还原你的原始数据框,方便复现操作:

df <- data.frame(
  year = c(2012, 2012, 2010, 2010, 2010, 2010, 2010, 2012),
  id = c(1, 1, 2, 2, 2, 2, 2, 2),
  value = c(180, 149, 131, 120, 120, 16, 120, 50),
  time = c(1, 1, 0, 0, 0, 0, 0, 1)
)

下面提供两种实现方式:

方法一:使用dplyr(tidyverse工具链)

按id分组后,检查该组是否同时包含2010和2012两个年份,再将布尔结果转为1/0的哑变量:

library(dplyr)

df <- df %>%
  group_by(id) %>%
  mutate(treated = as.integer(all(c(2010, 2012) %in% year))) %>%
  ungroup()

方法二:使用Base R(无需额外加载包)

先提取每个id对应的唯一年份,判断条件后再匹配回原数据框:

# 提取每个id的唯一年份集合
id_year_sets <- tapply(df$year, df$id, unique)

# 判断每个id是否同时包含2010和2012
id_flag <- sapply(id_year_sets, function(x) all(c(2010, 2012) %in% x))

# 将结果转为数据框并合并回原数据
flag_df <- data.frame(id = names(id_flag), treated = as.integer(id_flag))
df <- merge(df, flag_df, by = "id", sort = FALSE)

最终结果

运行任意一种方法后,得到的数据框如下(若需要将列名改为both,只需把代码中的treated替换成both即可):

> df
   year id value time treated
1 2012  1   180    1       0
2 2012  1   149    1       0
3 2010  2   131    0       1
4 2010  2   120    0       1
5 2010  2   120    0       1
6 2010  2    16    0       1
7 2010  2   120    0       1
8 2012  2    50    1       1

内容的提问来源于stack exchange,提问作者João Felix

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 13:35:19