繁体   English   中英

如果两列匹配,则将2个数据框连接在一起

[英]Join 2 dataframes together if two columns match

我有2个数据框:

乡村积分

From.country  To.Country points
Belgium       Finland    4
Belgium       Germany    5
Malta         Italy      12
Malta         UK         1

以及与邻国/邻国的另一个数据框:

From.country    To.Country 
    Belgium       Finland   
    Belgium       Germany   
    Malta         Italy   

我想在CountryPoints中添加另一列称为邻居(Y / N),具体取决于是否在邻居/边界国家/地区数据框中找到了键值对。 这有可能吗-所以它是一种联接,但结果应该是一个布尔列。

结果应为:

From.country  To.Country points  Neighbour
    Belgium       Finland    4    Y
    Belgium       Germany    5    Y
    Malta         Italy      12   Y
    Malta         UK         1    N

在下面的问题中,它显示了如何合并,但未显示如何添加该额外的布尔列

两种替代方法:

1)使用基数R:

idx <- match(df1$From.country, df2$From.country, nomatch = 0) &
  match(df1$To.Country, df2$To.Country, nomatch = 0)
df1$Neighbour <- c('N','Y')[1 + idx]

2)与data.table

library(data.table)
setDT(df1)
setDT(df2)

df1[, Neighbour := 'N'][df2, on = .(From.country, To.Country), Neighbour := 'Y'][]

两者都给出(显示了data.table ):

  From.country To.Country points Neighbour 1: Belgium Finland 4 Y 2: Belgium Germany 5 Y 3: Malta Italy 12 Y 4: Malta UK 1 N 

这篇文章中借用这个想法:

df1$Neighbour  <- duplicated(rbind(df2[, 1:2], df1[, 1:2]))[ -seq_len(nrow(df2)) ]

df1
#   From.country To.Country points Neighbour
# 1      Belgium    Finland      4      TRUE
# 2      Belgium    Germany      5      TRUE
# 3        Malta      Italy     12      TRUE
# 4        Malta         UK      1     FALSE

那这样的东西呢?

sortpaste <- function(x) paste0(sort(x), collapse = "_");
df1$Neighbour <- apply(df1[, 1:2], 1, sortpaste) %in% apply(df2[, 1:2], 1, sortpaste)
#  From.country To.Country points Neighbour
#1      Belgium    Finland      4      TRUE
#2      Belgium    Germany      5      TRUE
#3        Malta      Italy     12      TRUE
#4        Malta         UK      1     FALSE

样本数据

df1 <- read.table(text =
    "From.country  To.Country points
Belgium       Finland    4
Belgium       Germany    5
Malta         Italy      12
Malta         UK         1", header = T)

df2 <- read.table(text =
    "From.country    To.Country
    Belgium       Finland
    Belgium       Germany
    Malta         Italy", header = T)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM