在R中将两个具有不同行数的数据帧合并 [英] Combine two data frames with different number of rows in R

查看:423
本文介绍了在R中将两个具有不同行数的数据帧合并的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个数据帧,链接和正文:

I have two data frames, link and body:

链接是这样的:

wpt        ID
1          1235
mediate    4562
mediate    0928
2          6351
3          3826
mediate    0835

身体是这样的:

wpt   fuel    distance
1     2221    53927
2     4821    48261
3     8362    47151

我期望的输出是这样的:

The output i expected is like this:

wpt      fuel   distance   ID
1        2221   53927      1235
mediate  NA     NA         4562
mediate  NA     NA         0928
2        4821   48261      6351
3        8362   47151      3826
mediate  NA     NA         0835

我尝试使用合并"功能,但没有解决.假设使用"mediate"的行号作为索引来拆分"body"并逐块绑定它们可能会起作用.有更好的好方法吗?看到有人可以在这里帮忙吗?

I tried using "merge" function, did not work out. Suppose using row number of "mediate" as index to split "body" and rbind them piece by piece might work. Is there a better nice way? See someone could help here?

提前谢谢!

推荐答案

df1 <- data.frame(wpt = c(1, "meditate", "meditate", 2,3,"meditate"), 
              ID = c(1235, 4562, 0928,6351,3826,0835))
df1$wpt <- as.character(df1$wpt)


df2 <- data.frame(wpt = c(1,2,3), 
              fuel = c(1235, 4562, 0928), 
              distance = c(2,3,4))
df2$wpt <- as.character(df2$wpt)


library(dplyr)
full_join(df1, df2, by = "wpt")

不要介意价值观!您始终可以重新排列列.

Don't mind the values! You can always rearrange the columns.

       wpt   ID fuel distance
1        1 1235 1235        2
2 meditate 4562   NA       NA
3 meditate  928   NA       NA
4        2 6351 4562        3
5        3 3826  928        4
6 meditate  835   NA       NA

这篇关于在R中将两个具有不同行数的数据帧合并的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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