Combine two data frames with different number of rows in R
This question already has an answer 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
Here's a non-merge base R solution built around match()
:
link[names(body)[-1L]] <- body[match(link[,1L],body[,1L]),-1L];
link;
## wpt ID fuel distance
## 1 1 1235 2221 53927
## 2 mediate 4562 NA NA
## 3 mediate 0928 NA NA
## 4 2 6351 4821 48261
## 5 3 3826 8362 47151
## 6 mediate 0835 NA NA
Data
link <- data.frame(wpt=c('1','mediate','mediate','2','3','mediate'),ID=c('1235','4562','0928'
,'6351','3826','0835'),stringsAsFactors=F);
body <- data.frame(wpt=c(1L,2L,3L),fuel=c(2221L,4821L,8362L),distance=c(53927L,48261L,47151L)
);
我认为以下应该工作:
library(data.table)
setkey(link,wpt)
setkey(body,wpt)
merge(link,body,by="wpt",all.x=T)
链接地址: http://www.djcxy.com/p/24912.html
上一篇: Left,Right,Outer和Inner Joins之间有什么区别?
下一篇: 组合R中具有不同行数的两个数据帧