简体   繁体   中英

R: Finding values of one vector in another and corresponding values

If I have a data.frame (df1) as follows:

Name  Count
a     1
b     2
c     3

and another data.frame (df2) like:

Name  Count
aa     0
ba     0
ca     0
b      0
a      0
c      0

I want to get the values corresponding to df1 in df2, where the names match. I am currently trying:

idx = which(df2$Name %in% df1$Name)
df2[idx,2] = df1$Count

This seems to swap or permutes some of the stored counts. What would be a method where the order in the original data.frame can be preserved?

You can get the indices for replacement using match :

df2[match(df1$Name, df2$Name),]$Count <- df1$Count

As to why your solution doesn't work, compare the output of:

which(df2$Name %in% df1$Name)
[1] 4 5 6

and

match(df1$Name, df2$Name)
[1] 5 4 6

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM