【问题标题】:How to create new column based on two different length dataframe matching IDS in R如何基于两个不同长度的数据帧匹配 R 中的 IDS 创建新列
【发布时间】:2020-08-27 10:50:15
【问题描述】:

我有长度为 100 的 df1 看起来像

PID
123
234
T345
P456
567

我还有另一个长度为 1000 的 df2 看起来一样

PID
123
234
567
T678
P768
....

如果PIDdf2 状态为"1""0" 匹配,我需要在df1 中创建新列

预期输出:

PID    V1
123     1
234     1
T345    0
P456    0
567     1

我尝试了 ifelse 条件,但由于长度不均匀而发生错误。

提前致谢

【问题讨论】:

    标签: r dplyr tidyverse


    【解决方案1】:

    我建议使用base R 方法和match() 并使用ifelse

    #Data
    df1 <- structure(list(PID = c("123", "234", "T345", "P456", "567")), class = "data.frame", row.names = 2:6)
    df2 <- structure(list(PID = c("123", "234", "567", "T678", "P768")), row.names = 2:6, class = "data.frame")
    

    现在代码使用值之间的匹配,然后格式化为 0 或 1:

    #Match
    df1$NewVar <- df2[match(df1$PID,df2$PID),'PID']
    df1$NewVar <- ifelse(is.na(df1$NewVar),0,1)
    

    输出:

       PID NewVar
    1  123      1
    2  234      1
    3 T345      0
    4 P456      0
    5  567      1
    

    【讨论】:

      【解决方案2】:

      您可以尝试%in%,如下所示

      df1$V1 <- +(df1$PID %in% df2$PID)
      

      给了

      > df1
         PID V1
      1  123  1
      2  234  1
      3 T345  0
      4 P456  0
      5  567  1
      

      数据

      > dput(df1)
      structure(list(PID = c("123", "234", "T345", "P456", "567"), 
          V1 = c(1L, 1L, 0L, 0L, 1L)), row.names = c(NA, 5L), class = "data.frame")
      > dput(df2)
      structure(list(PID = c("123", "234", "567", "T678", "P768")), row.names = c(NA, 
      5L), class = "data.frame")
      

      【讨论】:

      • 我得到了您的提示代码的结果,但它与某些行不匹配,它们都在字符类中,我们还能做什么?
      • @Rebel_47 它似乎适用于您帖子中的示例,但我不知道您的真实数据会发生什么...
      猜你喜欢
      • 2021-09-02
      • 2020-10-10
      • 1970-01-01
      • 2022-11-02
      • 1970-01-01
      • 1970-01-01
      • 2016-08-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多