合并功能会混淆数据顺序

时间:2015-07-02 00:02:29

标签: r merge dataframe

我在df1中有一对原点和目的地点。我想使用a)来自Orig的{​​{1}}属性向此数据添加列。然后,我想从df2Dest列添加属性。问题是df3的顺序被重新排列,这不是我的意图。我的问题是如何在最终输出中保持行的顺序不变,而不需要在ID的开头添加额外的列,以后我可以对它进行排序?

原始表:

df1

我目前的结果

  Orig Dest
1    a    b
2    b    e
3    c    a
4    b    c
5    a    b
6    c    a
7    e    b

Orig = c("a","b","c","b","a","c","e")
Dest = c("b","e","a","c","b","a","b")

df1 = data.frame(Orig,Dest)

Code <- c("a","b","c","d","e")
Name <- c("Ams","Bir","Cas","Das","Ees")
Lat <- c(4,6,7,3,2)
Long <- c(13,45,63,43,23)
df2 <- data.frame(Code,Name,Lat,Long)
df3 <- data.frame(Code,Name,Lat,Long)
colnames(df2) <- c("Orig","Name","Lat","Long")
colnames(df3) <- c("Dest","Name","Lat","Long")

Result1 <- merge(df1,df2,by = c("Orig"), sort=FALSE) # tried without sort as well
Result2 <- merge(Result1,df3,by = c("Dest"), sort=FALSE)

期望的结果:

  Dest Orig Name.x Lat.x Long.x Name.y Lat.y Long.y
1    b    a    Ams     4     13    Bir     6     45
2    b    a    Ams     4     13    Bir     6     45
3    b    e    Ees     2     23    Bir     6     45
4    e    b    Bir     6     45    Ees     2     23
5    c    b    Bir     6     45    Cas     7     63
6    a    c    Cas     7     63    Ams     4     13
7    a    c    Cas     7     63    Ams     4     13

1 个答案:

答案 0 :(得分:0)

因此,根据您是否希望属性与Orig或Dest匹配,只需更改它,但您可以使用Orig或Dest对df2的属性进行排序:

df2[charmatch(Orig,Code),]

然后从df1

添加回Dest / Orig列