问题
I have two data frames, link and body:
link is like this:
wpt ID
1 1235
mediate 4562
mediate 0928
2 6351
3 3826
mediate 0835
body is like this:
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
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?
Thanks in advance!
回答1:
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
回答2:
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)
);
回答3:
I think the following should work :
library(data.table)
setkey(link,wpt)
setkey(body,wpt)
merge(link,body,by="wpt",all.x=T)
回答4:
We can use left_join
library(dplyr)
mutate(df2, wpt = as.character(wpt)) %>%
left_join(df1, ., by = 'wpt')
# wpt ID fuel distance
#1 1 1235 2221 53927
#2 mediate 4562 NA NA
#3 mediate 928 NA NA
#4 2 6351 4821 48261
#5 3 3826 8362 47151
#6 mediate 835 NA NA
Or using data.table
library(data.table)
setDT(df2)[, wpt := as.character(wpt)][df1, on = "wpt"]
# wpt fuel distance ID
#1: 1 2221 53927 1235
#2: mediate NA NA 4562
#3: mediate NA NA 928
#4: 2 4821 48261 6351
#5: 3 8362 47151 3826
#6: mediate NA NA 835
来源:https://stackoverflow.com/questions/38066077/combine-two-data-frames-with-different-number-of-rows-in-r