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

R语言使用filter()筛选数据报错:无法处理含重复列名的数据框

解决dplyr::filter()因数据框列名重复报错的问题

问题描述

运行R脚本筛选数据框indicator3中Italy和Argentina的数据时,出现以下报错:

Error in filter():
! Can't transform a data frame with duplicate names.
回溯信息:

  1. dplyr::filter(indicator3, country %in% c("Italy", "Argentina"))
  2. dplyr:::filter.data.frame(indicator3, country %in% c("Italy", "Argentina"))
    Error in filter(indicator3, country %in% c("Italy", "Argentina")) :

错误原因

indicator3数据框存在重复的列名,dplyr的filter()函数无法处理列名重复的数据框。

解决步骤

  1. 检查重复列名
    执行以下代码查看数据框的列名及重复项:
# 查看所有列名
colnames(indicator3)
# 找出重复的列名
table(colnames(indicator3))[table(colnames(indicator3)) > 1]
  1. 重命名重复列名
    用make.names()函数生成唯一列名并赋值给数据框:
# 生成唯一列名(重复列会自动添加后缀区分)
unique_colnames <- make.names(colnames(indicator3), unique = TRUE)
# 更新数据框列名
colnames(indicator3) <- unique_colnames
  1. 重新执行筛选操作
    列名处理完成后,再运行筛选代码即可:
library(dplyr)
# 管道写法
ItalyAng <- indicator3 %>% filter(country %in% c('Italy', 'Argentina'))
# 普通写法
# ItalyAng <- filter(indicator3, country %in% c('Italy', 'Argentina'))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 02:55:06