R - 使用另一个数据帧的匹配值将新列添加到数据框

时间:2021-09-21 04:51:39

I am trying to fill in table1 with matching val2 values of table2

我试图填写table1与table2的val2值匹配

table1$New_val2 = table2[table2$pid==table1$pid,]$val2

R  - 使用另一个数据帧的匹配值将新列添加到数据框

But I get the warning

但是我得到了警告

longer object length is not a multiple of shorter object length

which is fair enough because the table lengths are not the same.

这是公平的,因为表长度不一样。

Please kindly direct me on the correct way to do this.

请以正确的方式指导我这样做。

3 个解决方案

#1


17  

merge(table1, table2[, c("pid", "col2")], by="pid")

合并(table1,table2 [,c(“pid”,“col2”)],by =“pid”)

Add in the all.x=TRUE argument in order to keep all of the pids in table1 that don't have matches in table2.

添加all.x = TRUE参数以保持table1中table2中没有匹配项的所有pid。

You were on the right track. Here's a way using match...

你走在正确的轨道上。这是使用匹配的一种方式......

table1$val2 <- table2$val2[match(table1$pid, table2$pid)]

table1 $ val2 < - table2 $ val2 [match(table1 $ pid,table2 $ pid)]

#2


3  

I am not sure if you mean this but you might use:

我不确定你是否意味着这个,但你可以使用:

newtable <- merge(table1,table2, by  = "pid") 

This will create a new table called newtable, with 3 columns and those values matched by the id, in this case "pid".

这将创建一个名为newtable的新表,其中包含3列,并且这些值与id匹配,在本例中为“pid”。

#3


0  

I'm way late here, but in case anybody else asks the same question:
This is exactly what dplyr's inner_merge does.

我在这里已经很晚了,但万一其他人问同样的问题:这正是dplyr的inner_merge所做的。

table1.df <- dplyr::inner_merge(table1, table2, by=pid)

The by-command specifies which column should be used to match the rows.

by-command指定应使用哪个列来匹配行。

#1


17  

merge(table1, table2[, c("pid", "col2")], by="pid")

合并(table1,table2 [,c(“pid”,“col2”)],by =“pid”)

Add in the all.x=TRUE argument in order to keep all of the pids in table1 that don't have matches in table2.

添加all.x = TRUE参数以保持table1中table2中没有匹配项的所有pid。

You were on the right track. Here's a way using match...

你走在正确的轨道上。这是使用匹配的一种方式......

table1$val2 <- table2$val2[match(table1$pid, table2$pid)]

table1 $ val2 < - table2 $ val2 [match(table1 $ pid,table2 $ pid)]

#2


3  

I am not sure if you mean this but you might use:

我不确定你是否意味着这个,但你可以使用:

newtable <- merge(table1,table2, by  = "pid") 

This will create a new table called newtable, with 3 columns and those values matched by the id, in this case "pid".

这将创建一个名为newtable的新表,其中包含3列,并且这些值与id匹配,在本例中为“pid”。

#3


0  

I'm way late here, but in case anybody else asks the same question:
This is exactly what dplyr's inner_merge does.

我在这里已经很晚了,但万一其他人问同样的问题:这正是dplyr的inner_merge所做的。

table1.df <- dplyr::inner_merge(table1, table2, by=pid)

The by-command specifies which column should be used to match the rows.

by-command指定应使用哪个列来匹配行。