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

R语言merge函数报错:'by'必须指定唯一有效列求助

R语言merge左连接报错排查与解决

错误原因

你执行merge时犯了一个低级错误:把y参数传成了向量ProductPurchased,但merge要求x和y必须都是数据框类型。向量里根本没有名为"Emails"的列,自然会触发'by' must specify a uniquely valid column的报错。

修正后的代码

把y = ProductPurchased改成你之前创建的Purchases数据框即可,完整代码如下:

Emails <- c("Bob@gmail.com","Mike@aol.com","Lyndsey@blue.com","Ethan@gmail.com","Sara@gmail.com",
           "Sarah@yahoo.com","Leo@stuff.com","Raj@blue.com")
State <- c("Washington","California","Texas","Iowa","New York","California","Alabama","Alaska")
PPP <- data.frame(Emails = Emails,State = State)

Emails <- c("Bob@gmail.com","Mike@aol.com","Lyndsey@blue.com","Ethan@gmail.com","Sara@gmail.com",
           "Sarah@yahoo.com","Leo@stuff.com","Raj@blue.com","Lyndsey@blue.com","Ethan@gmail.com","Sara@gmail.com",
           "Sarah@yahoo.com","Leo@stuff.com","Raj@blue.com","Mike@aol.com","Lyndsey@blue.com","Ethan@gmail.com","Sara@gmail.com",
           "Sarah@yahoo.com","Leo@stuff.com")
ProductPurchased <- c("Hat","Bat","Cat","Hat","Candy","Fruit","Candy","Cat","Hat","Candy","Fruit",
                      "Candy","Cat","Hat","Candy","Fruit","Candy","Cat","Hat","Candy")
Purchases <- data.frame(Emails = Emails,ProductPurchased = ProductPurchased)

# 修正后的左连接语句
Left <- merge(x = PPP, y = Purchases, by.x = "Emails", by.y = "Emails", all.x = TRUE)

效果说明

修正后执行代码,就能正常完成左连接:PPP里的所有用户都会被保留,有购买记录的用户会对应显示购买的产品,没有购买记录的用户(比如Bob)的ProductPurchased列会显示为NA。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 18:10:26