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

如何使用R Tidyverse为数据集参与者分配从1开始的新连续ID

解决方案

你不需要对数据集做长宽转换,直接为每个唯一的原始ID映射一个从1开始的连续整数即可,以下是两种常用实现方式:

方法1:使用tidyverse(dplyr)实现

# 加载依赖包
library(dplyr)

# 读入示例数据
df <- structure(list(id = c(1001L, 1001L, 1001L, 1001L, 1001L, 1001L, 1001L, 1001L, 1001L, 1002L, 1002L), condition_a = c("a", "a", "a", "b", "b", "b", "c", "c", "c", "a", "a"), condition_b = c("aa", "aa", "aa", "aa", "aa", "aa", "aa", "aa", "aa", "bb", "bb"), condition_c = c("abc", "abc", "abc", "abc", "abc", "abc", "abc", "abc", "abc", "abc", "abc"), condition_d = c(10L, 10L, 10L, 10L, 10L, 10L, 10L, 10L, 10L, 15L, 15L), items = c("a", "b", "c", "d", "e", "f", "g", "h", "i", "a", "b"), response = c(0L, 1L, 0L, 1L, 0L, 1L, 0L, 1L, 0L, 1L, 0L)), class = "data.frame", row.names = c(NA, -11L))

# 替换id列为从1开始的连续新ID
df_new <- df %>%
  mutate(id = as.integer(factor(id, levels = unique(id))))

# 等价实现方式:使用group_indices生成分组序号
# df_new <- df %>% mutate(id = group_indices(., id))

运行后原ID为1001的所有行都会被替换为1,原ID为1002的所有行都会被替换为2,完全保留长表原有结构,适配后续GLMM分析需求。

方法2:使用基础R实现

如果不想加载额外依赖包,用基础R语句也可以快速完成替换:

df$id <- as.integer(factor(df$id, levels = unique(df$id)))

内容的提问来源于stack exchange,提问作者user8460166

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 14:54:05