【问题标题】:How to add data from one data set to another in R?如何将数据从一个数据集添加到 R 中的另一个数据集?
【发布时间】:2021-06-07 20:10:01
【问题描述】:

您好,我想合并两个数据集,并将一个数据集 (Df2$IgA_Titre) 中的数据整合到我的原始数据集 Df1 的同一列中,该列缺少数据。

不幸的是,因为它们是公共变量,我认为 R 也会尝试基于 IgA_titre 进行合并,即使我指定了要合并的变量。结果数据没有被添加,我仍然缺少 IgA 的值。

我已经尝试了以下代码和各种 dplyr/mutate 替代方案,但它仍然无法整合数据

test <- left_join(Df1, Df2, by = c("Sample_ID", "Visit"))

#Df1
    Sample_ID    Visit IgA_Titre Vi.IgG1.G0
1      8016  Pre-Vac        NA  0.12     
2      8016 Post-Vac        NA  0.15 
3      8034  Pre-Vac        NA  0.13  
4      8034 Post-Vac        NA  0.17  


#Df2
    Sample_ID   Visit IgA_Titre
1      8016 Pre-Vac    1.5625
2      8016 Post-Vac   1.5625
3      8034 Pre-Vac    1.5625
4      8034 Post-Vac   11.5965


任何见解将不胜感激!

【问题讨论】:

    标签: r dataframe dplyr merge data.table


    【解决方案1】:
    library(data.table)
    setDT(df1)[, IgA_Titre := as.numeric(IgA_Titre)]  # tidy IgA_Titre column as numeric type
    df1[df2, IgA_Titre := i.IgA_Titre, on = .(Sample_ID, Visit)] # perform join
    df1
    #   Sample_ID    Visit IgA_Titre Vi.IgG1.G0
    #1:      8016  Pre-Vac    1.5625       0.12
    #2:      8016 Post-Vac    1.5625       0.15
    #3:      8034  Pre-Vac    1.5625       0.13
    #4:      8034 Post-Vac   11.5965       0.17
    

    【讨论】:

    • 谢谢你的工作!我会详细阅读 data.table 包,它似乎派上用场了
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-12-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-24
    • 2016-09-08
    相关资源
    最近更新 更多