【问题标题】:Is there an R function for "Left_Join" but without keeping all combinations of Matches? [duplicate]是否有“Left_Join”的 R 函数但不保留所有匹配组合? [复制]
【发布时间】:2023-03-20 11:43:01
【问题描述】:

我想将特定列中的值匹配到不同的数据框,并仅检索第一个匹配项的整行数据,而不是所有组合。

我尝试使用 left_join,但它只是检索所有数据。下面是一个例子:

# First table
cusip <- c("AAA1", "AAA2","AAA3")
Datecode <- c("201912", "202003", "202006")
FirstTable <- data_frame(cusip,Datecode)


#Lookuptable
cusip <- c("AAA1", "AAA1","AAA2","AAA2","AAA3","AAA3")
Name <- c("Facebook Inc", "Facebook", "Apple","Apple INC", "Amz", "Amazon")
LookupTable <- data_frame(cusip,Name)

所以我想要的是在 FirstTable 中创建一个从查找表中检索名称的名称列。但是,我不在乎 AAA1 是 Facebook 还是 Facebook Inc。

一个简单的 Left_join 保留所有组合,所以当我只想要 3 行时给我 6 行。

希望有人能帮忙,谢谢!

  • R 相对较新的用户

【问题讨论】:

  • 在您加入之前,您可以使 LookupTable 由 cusip 唯一,默认情况下将保留每个实例的第一个实例。
  • 谢谢,我已尝试通过 Cusip 使其唯一,但此功能会删除所有其他列?还是我做错了什么? ´´´ Lookuptable
  • 尝试dplyr::distinct(LookupTable, cusip, .keep_all = T) 使用dplyr 包或在基础R 中:LookupTable[!duplicated(cusip),]。

标签: r


【解决方案1】:
library(dplyr)
left_join(FirstTable, 
          LookupTable %>% group_by(cusip) %>% slice(1))

Joining, by = "cusip"
# A tibble: 3 x 3
  cusip Datecode Name        
  <chr> <chr>    <chr>       
1 AAA1  201912   Facebook Inc
2 AAA2  202003   Apple       
3 AAA3  202006   Amz  

【讨论】:

    【解决方案2】:

    快速data.table 接近

    library(data.table)
    #make them data.tables
    setDT(LookupTable); setDT(FirstTable)
    #perform update join
    FirstTable[ LookupTable, Name := i.Name, on = .(cusip)]
    
    #    cusip Datecode      Name
    # 1:  AAA1   201912  Facebook
    # 2:  AAA2   202003 Apple INC
    # 3:  AAA3   202006    Amazon
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-31
      • 2021-10-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-07
      相关资源
      最近更新 更多