使用tibble::rownames_to_column报错:.data参数需唯一列名
解决
tibble::rownames_to_column报错:重复列名问题 问题重现
执行代码将行名转为Sample列时触发错误:
df <- tibble::rownames_to_column(df, "Sample")
报错信息:
Error: ! The `.data` argument of `add_column()` must have unique names as of tibble 3.0.0. ℹ Use `.name_repair = "minimal"`. Run `rlang::last_trace()` to see where the error occurred.
核心原因
你的数据框存在重复列名:samID和clust各出现两次,而tibble 3.0.0及之后版本强制要求数据框列名唯一,这是报错的直接原因。
解决方案
步骤1:处理重复列名
你可以选择自动给重复列名添加后缀,或者手动重命名:
- 自动添加后缀(快速处理):
colnames(df) <- make.unique(colnames(df))
执行后重复列名会自动变为samID/samID.1、clust/clust.1的格式。
- 手动重命名(更灵活可控):
# 定位重复列并自定义命名 samid_pos <- which(colnames(df) == "samID") colnames(df)[samid_pos] <- c("samID", "samID_dup") clust_pos <- which(colnames(df) == "clust") colnames(df)[clust_pos] <- c("clust", "clust_dup")
步骤2:执行行名转列操作
处理完重复列名后,再运行原代码即可成功:
df <- tibble::rownames_to_column(df, "Sample")
验证结果
可以通过以下命令确认处理后的数据结构:
str(df)
内容的提问来源于stack exchange,提问作者Anon
相关产品推荐
相关产品推荐

