将数据帧中的值与其他数据帧中的值进行匹配,并将其替换为来自其他数据帧的相应模式 [英] Match values in data frame with values in another data frame and replace former with a corresponding pattern from the other data frame

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

问题描述

复杂的标题,但这里是一个简单的例子,我正在尝试实现:

  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 ,B),
v4 = c(d,e,a,c,d,b))

d $ v2 中的值应由 m中的值替换$ v4 通过匹配 d $ v2 m $ v3

生成的数据框架 d 应如下所示:

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

我尝试过不同的东西,最近我来的是:code> d $ v2< - m $ v4 [哪个(m $ v3%,%d $ v2)]



尝试避免任何for-loop再次!必须有可能:-)某种程度...;)

解决方案

您可以尝试:

  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



修改



这是另一种方法来保存订单:

  data.frame(v1 = d $ v1,v4 = m [比赛(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


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"))

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

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

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

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

解决方案

You could try:

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天全站免登陆