【问题标题】:Merging Two Datasets Using Different Column names: left_Join使用不同的列名合并两个数据集:left_Join
【发布时间】:2020-02-03 22:35:50
【问题描述】:

我正在尝试使用两个单独的列名合并两个数据集,但它们共享相同的唯一值。例如,数据集 1 中的列 A == xyzw,而在数据集 2 中,列的名称是 B,但值 == xyzw。

但是,问题在于,在数据集 2 中,列的 B 值 == xyzw 指的是公司名称并出现多次,具体取决于数据集中存在该公司的员工数量。

基本上,我想创建一个新列,我们在数据集 1 中将其称为 C,告诉我每个公司有多少员工。

我尝试了以下方法:

## Counting how many teachers are in each matched school, using the "Matched" column from matching_file_V4, along with the school_name column from the sample11 dataset:
merged_dataset <- left_join(sample11,matched_datasets,by="school_name")

虽然此代码有效,但它并没有真正为我提供每家公司的员工人数。

【问题讨论】:

    标签: r dplyr left-join tidyverse


    【解决方案1】:

    如果您可以提供示例数据和预期的输出,它会让其他人更容易提供帮助。但尽管如此,我希望这能满足您的需求:

    假设我们有这两个数据框:

    df_1 <- data.frame(
      A = letters[1:5],
      B = c('empl_1','empl_2','empl_3','empl_4','empl_5')
    )
    
    df_2 <- data.frame(
      C = sample(rep(c('empl_1','empl_2','empl_3','empl_4','empl_5'), 15), 50),
      D = sample(letters[1:5], 50, replace=T)
    )
    
    
    # I suggest you find the number of employees for each firm in the second data frame  
    
    
    df_2%>%group_by(C)%>%
      summarise(
        num_empl = n()
      )%>%  ### Then do the left join
      left_join(
        df_1,., by=c('B' = 'C') ## this is how you can join on two different column names
      )
    
    #   A      B num_empl
    # 1 a empl_1        8
    # 2 b empl_2       11
    # 3 c empl_3       10
    # 4 d empl_4       10
    # 5 e empl_5       11
    

    【讨论】:

      猜你喜欢
      • 2018-06-25
      • 1970-01-01
      • 2022-01-10
      • 1970-01-01
      • 1970-01-01
      • 2021-12-28
      • 1970-01-01
      • 1970-01-01
      • 2021-11-19
      相关资源
      最近更新 更多