【问题标题】:Replacing column values if they match one of two columns in another dataset如果列值与另一个数据集中的两列之一匹配,则替换它们
【发布时间】:2022-11-25 21:34:15
【问题描述】:

我有如下示例数据:

library(data.table)
dat1 <- fread("code1 code2 code3
              A3     B2   C1
              A4     B3   C2")

dat2 <- fread("codes
              A3  
              A4
              B2
              B3")

我只想用 dat1 中的 code3 替换 dat2 中的代码。

期望的输出:

dat_out <- fread("codes
              C1  
              C2
              C1
              C2")

我应该怎么做?

【问题讨论】:

    标签: r dplyr data.table


    【解决方案1】:

    你可以使用match

    `%r%`<- function(x, y) replace(x %% y, x %% y == 0, y)
    dat2[, codes := dat1$code3[match(dat2$codes, unlist(dat1)) %r% nrow(dat1)]]
    
    #   codes
    #1:    C1
    #2:    C2
    #3:    C1
    #4:    C2
    

    解释:

    • 这在 dat1unlisted 值上使用 match(您也可以只关注选定的列)。
    • 然后您可以使用%%(取模)得到除以nrow(dat1)的其余整数。基本上,它恢复了列的大小(重新列出)。
    • 问题是它在我们需要 2(或nrow)的地方创建了值 0,因此需要 new 运算符。

    【讨论】:

      【解决方案2】:

      这可能是一种方法:

      library(tidyverse)
      
      dat2 %>% 
        inner_join(dat1 %>% pivot_longer(!code3), by = c('codes'='value')) %>%
        select(!name) %>%
        mutate(codes = coalesce(!!!rev(.))) %>%
        select(codes)
      
         codes
      1:    C1
      2:    C2
      3:    C1
      4:    C2
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-05-18
        • 2017-03-04
        • 1970-01-01
        • 2015-02-11
        • 2022-01-13
        • 2023-03-12
        • 2015-12-14
        相关资源
        最近更新 更多