将列从另一个数据框中复制到基于另一个数据框中的行名称 [英] Copy column from another data frame to based on row names from a different data frame

查看:78
本文介绍了将列从另一个数据框中复制到基于另一个数据框中的行名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有几个数据帧,两者中的某些行名都相同。我想从第一个数据帧中复制第二个数据帧中存在的所有行名的列。第一个数据帧(df1)看起来像是

I have a couple of data frames, some of the row names in both are the same. I want to copy a column from first data frame for all the row names that are present in second data frame. First data frame (df1) looks like

        m1      m2     m3
P001   60.00   2.0     1
P002   14.30   2.077   1
P003   29.60   2.077   1
P004   10.30   2.077   1
P006   79.30   2.077   1
P008    9.16   2.077   1

,第二个数据帧(df2)看起来像是

and the second data frame (df2) looks like

        n1      n2   n3
P001   12.00   2.0   1
P003   17.60   1.7   1
P005   22.30   2.7   1
P006   26.30   1.7   1

我想为第二个数据帧中存在的所有行名称(即P001,P003,P005和P006)使用变量m1(df1 $ m1)。如果df1中不存在某些行名(例如P005),则可以将其替换为NA或0。

I want to have variable m1 (df1$m1) for all row names present in second data frame( i.e P001, P003, P005, and P006). If some row names does not exist in df1 (eg P005), it could be replaced with NA or 0.

答案可能是这样的

       m1           
P001   60.00
P003   29.60
P005   NA
P006   79.30 

更长的选择是使用循环,但是我确信R应该有一个捷径。

The longer option would be to use loops but I am sure R should have a shortcut.

推荐答案

data.table 对象不保留行名(尽管它将其存储为属性),但是您可以使用 keep.rownames = TRUE将行名转换为其他列,同时转换为 data.table ,然后在键入键之后,可以使用二进制连接并通过引用更新 df2 来连接数据集(类似于@eddies链接)

data.table object doesn't keep row names (although it has it stored as an attribute) but you can convert the row names to an additional column while converting to data.table using keep.rownames = TRUE and then, after keying, you can join the data sets using the binary join and while updating df2 by reference (similarly to @eddies link)

setDT(df1, keep.rownames = TRUE)
setkey(setDT(df2, keep.rownames = TRUE), rn)
df2[df1, m1 := i.m1][]
#      rn   n1  n2 n3   m1
# 1: P001 12.0 2.0  1 60.0
# 2: P003 17.6 1.7  1 29.6
# 3: P005 22.3 2.7  1   NA
# 4: P006 26.3 1.7  1 79.3

这篇关于将列从另一个数据框中复制到基于另一个数据框中的行名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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