我有两个数据框,链接和正文:
链接是这样的:
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
我预期的输出是这样的:
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
我尝试使用" merge"功能,没有成功。假设使用"调整"的行号。作为拆分" body"的索引并且他们一块一块地工作可能会起作用。有更好的方式吗?看到有人可以帮忙吗?
提前致谢!
答案 0 :(得分:3)
这是围绕match()
构建的非合并基础R解决方案:
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
数据强>
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)
);
答案 1 :(得分:2)
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")
不介意价值观!您可以随时重新排列列。
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 :(得分:2)
我认为以下内容应该有效:
library(data.table)
setkey(link,wpt)
setkey(body,wpt)
merge(link,body,by="wpt",all.x=T)
答案 3 :(得分:1)
我们可以使用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
或使用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