R-使用另一个数据框的匹配值将新列添加到数据框 [英] R - Add a new column to a dataframe using matching values of another dataframe

查看:1067
本文介绍了R-使用另一个数据框的匹配值将新列添加到数据框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试用匹配的table2的val2值填充table1

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

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

但是我得到警告

longer object length is not a multiple of shorter object length

这很公平,因为表的长度不同.

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

请指导我正确的方法.

推荐答案

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

添加all.x=TRUE参数,以便将table1中所有不匹配的pid保留在table2中.

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

您在正确的轨道上.这是使用match的一种方法...

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

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

这篇关于R-使用另一个数据框的匹配值将新列添加到数据框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆