我正在尝试使用table2的匹配val2值填充table1
table1$New_val2 = table2[table2$pid==table1$pid,]$val2
但我收到了警告
longer object length is not a multiple of shorter object length
这是公平的,因为表长度不一样。
请以正确的方式指导我。
答案 0 :(得分:23)
merge(table1, table2[, c("pid", "col2")], by="pid")
添加all.x=TRUE
参数,以保持table1中table2中没有匹配项的所有pid。
你走在正确的轨道上。这是使用匹配的方式...
table1$val2 <- table2$val2[match(table1$pid, table2$pid)]
答案 1 :(得分:3)
我不确定你的意思,但你可以使用:
newtable <- merge(table1,table2, by = "pid")
这将创建一个名为newtable的新表,其中包含3列,并且这些值与id匹配,在本例中为“pid”。
答案 2 :(得分:0)
我在这里已经很晚了,但万一有人提出同样的问题: 这正是dplyr的inner_merge所做的。
table1.df <- dplyr::inner_merge(table1, table2, by=pid)
by-command指定应使用哪个列来匹配行。