将数据框中的值与另一个数据框中的值匹配,并用另一个数据框中的相应模式替换前者 [英] Match values in data frame with values in another data frame and replace former with a corresponding pattern from the other data frame

查看:26
本文介绍了将数据框中的值与另一个数据框中的值匹配,并用另一个数据框中的相应模式替换前者的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

复杂的标题,但这是我想要实现的一个简单示例:

Complicated title but here is a simple example of what I am trying to achieve:

d <- data.frame(v1 = c(1,2,3,4,5,6,7,8), 
                v2 = c("A","E","C","B","B","C","A","E"))

m <- data.frame(v3 = c("D","E","A","C","D","B"), 
                v4 = c("d","e","a","c","d","b"))

d$v2 中的值应替换为 m$v4 中的值,方法是匹配 d$v2 中的值m$v3

Values in d$v2 should be replaced by values in m$v4 by matching the values from d$v2 in m$v3

结果数据框 d 应如下所示:

The resulting data frame d should look like:

v1    v4
1      a
2      e
3      c
4      b
5      b
6      c
7      a
8      e

我尝试了不同的东西,最接近的是:d$v2 <- m$v4[which(m$v3 %in% d$v2)]

I tried different stuff and the closest I came was: d$v2 <- m$v4[which(m$v3 %in% d$v2)]

我再次尝试避免任何 for 循环!一定是可能的 :-) 不知何故... ;)

I try to avoid any for-loops again! Must be possible :-) somehow... ;)

推荐答案

你可以试试:

merge(d,m, by.x="v2", by.y="v3")
  v2 v1 v4
1  A  1  a
2  A  7  a
3  B  4  b
4  B  5  b
5  C  3  c
6  C  6  c
7  E  2  e
8  E  8  e

编辑

这是另一种保持顺序的方法:

Edit

Here is another approach, to preserve the order:

data.frame(v1=d$v1, v4=m[match(d$v2, m$v3), 2])
  v1 v4
1  1  a
2  2  e
3  3  c
4  4  b
5  5  b
6  6  c
7  7  a
8  8  e

这篇关于将数据框中的值与另一个数据框中的值匹配,并用另一个数据框中的相应模式替换前者的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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