R 如果两列的组合正好匹配其他两列,则子集数据帧
我有类似的数据R 如果两列的组合正好匹配其他两列,则子集数据帧,r,R,我有类似的数据 x1 <- data.frame(state = c("FL","FL","TX","TX"), county = c("Duval","Columbia","Dallam","Dimmit")) x2 <- data.frame(state = c("FL","FL","FL","TX","TX","TX"), county = c("Duval","Columbia","Pinellas","Dallam","Dimmit","Duval"), UR = c(4,
x1 <- data.frame(state = c("FL","FL","TX","TX"), county = c("Duval","Columbia","Dallam","Dimmit"))
x2 <- data.frame(state = c("FL","FL","FL","TX","TX","TX"), county = c("Duval","Columbia","Pinellas","Dallam","Dimmit","Duval"), UR = c(4,5,7,4,6,3))
x3 <- subset(x2, county %in% x1$county & state %in% x1$state)
x1您要查找的是左连接:
> library(dplyr)
> left_join(x1, x2, by = c('state', 'county'))
state county UR
1 FL Duval 4
2 FL Columbia 5
3 TX Dallam 4
4 TX Dimmit 6
或使用基本R中的合并
:
> merge(x1, x2, all.x = T)
state county UR
1 FL Columbia 5
2 FL Duval 4
3 TX Dallam 4
4 TX Dimmit 6
使用数据表
library(data.table)
setDT(x2)[x1, on = .(state, county)]
# state county UR
#1: FL Duval 4
#2: FL Columbia 5
#3: TX Dallam 4
#4: TX Dimmit 6
尝试查找:?合并
。很好,就是这样。谢谢您!