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

在R中去除两列重复行后行数未减少,请求排查代码错误

我帮你拆解下这段R代码里的问题,为啥去重后行数没变化,主要是几个关键错误导致的:

1. 去重结果没有赋值回变量

你现在的代码里,比如sort.Test_new[!duplicated(...), ]和sort.Test_new %>% distinct(...)只是临时执行了去重操作,但没有把结果重新赋值给原变量(或新变量)。R里大多数操作不会直接修改原对象,必须显式赋值才能更新数据。

举个正确的例子:

# 把去重后的结果存回sort.Test_new,覆盖原数据
sort.Test_new <- sort.Test_new %>% distinct(code, Brand, .keep_all = TRUE)

# 或者用duplicated的正确写法
sort.Test_new <- sort.Test_new[!duplicated(sort.Test_new[c("Brand", "code")]), ]

如果不做赋值,原数据sort.Test_new完全不会改变,行数自然和初始状态一致。

2. duplicated函数参数使用错误

你写的!duplicated(sort.Test_new$Brand,sort.Test_new$code)是错误的:duplicated的第二个参数是fromLast(逻辑值,控制从末尾开始判断重复),不是第二列的名称。要基于多列判断重复,必须把这些列打包成一个数据框/矩阵传入:

# 基于Brand和code两列判断重复
!duplicated(sort.Test_new[c("Brand", "code")])

你原来的写法相当于只检查Brand列的重复,第二列被错误当成了fromLast参数(会被强制转成逻辑值,逻辑完全混乱),根本没实现“两列共同去重”的需求。

3. 处理sort.Test_md时引用了错误的数据集列

你在这段代码里犯了低级错误:

sort.Test_md[!duplicated(sort.Test_new$Brand,sort.Test_md$`State Product Code`), ]

你要去重的是sort.Test_md,却引用了sort.Test_new$Brand——跨数据集拿列会导致判断逻辑完全错误,甚至可能因为列长度不匹配抛出异常。正确的写法是用sort.Test_md自己的Brand列:

sort.Test_md <- sort.Test_md[!duplicated(sort.Test_md[c("Brand", "State Product Code")]), ]

# 或者用distinct更简洁
sort.Test_md <- sort.Test_md %>% distinct(Brand, `State Product Code`, .keep_all = TRUE)

修正后的完整关键代码

library(readxl)
library(dplyr) # tidyverse已包含dplyr,无需重复加载

# 读取数据
Test_1 <- read_excel("SGWS/Test 1.xlsx")
test_2 <- read_excel("SGWS/Test 2.xlsx")

# 重命名列
names(Test_1)[names(Test_1)=="Brand Name Final"] <- "Brand"

# 排序(用dplyr的arrange更清晰)
sort.Test_new <- Test_1 %>% arrange(Brand, code)
sort.Test_md <- test_2 %>% arrange(Brand, `State Product Code`)

# 查看初始行数
nrow(sort.Test_new)
nrow(sort.Test_md)

# 去重并赋值回变量
sort.Test_new <- sort.Test_new %>% distinct(code, Brand, .keep_all = TRUE)
sort.Test_md <- sort.Test_md %>% distinct(Brand, `State Product Code`, .keep_all = TRUE)

# 再次查看行数,确认去重生效
nrow(sort.Test_new)
nrow(sort.Test_md)

# 后续合并与筛选
Assignment <- merge(x=sort.Test_md, y=sort.Test_new, by ="Brand", all.x=TRUE)
AssignmentFinal <- subset(Assignment, Flag=="MD")
nrow(AssignmentFinal)

内容的提问来源于stack exchange,提问作者G.Aurelien

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.08 23:17:32