【问题标题】:Conditional search, match and replace values between data frames数据框之间的条件搜索、匹配和替换值
【发布时间】:2019-03-23 02:49:43
【问题描述】:

我有两个数据框,如下所示。当有匹配时,我想用从数据框 2 中获取的相应值替换数据框 1 中的文本(单元格)。我试图在下面举一个简单的例子。 我对 R 的经验有限,但无法立即想到一个简单的解决方案。任何帮助/建议将不胜感激。

input_1 = data.frame(col1 = c("ex1", "ex2", "ex3", "ex4"), 
                     col2 = c("A", "B", "C", "D"),
                     col3 = c("B", "E", "F", "D"))

input_2 = data.frame(colx = c("A", "B", "C", "D", "E", "F"), 
                coly = c(1, 2, 3, 4, 5, 6))

output = data.frame(col1 = c("ex1", "ex2", "ex3", "ex4"), 
                    col2 = c(1, 2, 3, 4),
                    col3 = c(2, 5, 6, 4))

【问题讨论】:

    标签: r dataframe tidyverse


    【解决方案1】:

    这是一个 tidyverse 解决方案:

    library(tidyverse)
    mutate_at(input_1, -1, ~deframe(input_2)[as.character(.)])
    #   col1 col2 col3
    # 1  ex1    1    2
    # 2  ex2    2    5
    # 3  ex3    3    6
    # 4  ex4    4    4
    

    deframe 从数据框构建命名向量,在这种情况下更方便。

    as.character 是必需的,因为您有因子列

    【讨论】:

      【解决方案2】:

      使用 tidyverse 的示例。我的解决方案涉及两次合并到 input_2,但匹配不同的列。最后一个管道清理数据框并重命名列。

      library(tidyverse)
      
      input_1 = data.frame(col1 = c("ex1", "ex2", "ex3", "ex4"), 
                           col2 = c("A", "B", "C", "D"),
                           col3 = c("B", "E", "F", "D"))
      
      input_2 = data.frame(colx = c("A", "B", "C", "D", "E", "F"), 
                      coly = c(1, 2, 3, 4, 5, 6))
      
      
      output = data.frame(col1 = c("ex1", "ex2", "ex3", "ex4"), 
                          col2 = c(1, 2, 3, 4),
                          col3 = c(2, 5, 6, 4))
      
      
      input_1 %>% inner_join(input_2, by = c("col2" = "colx")) %>%
          inner_join(input_2, by = c("col3" = "colx")) %>% 
          select(col1, coly.x, coly.y) %>%
          magrittr::set_colnames(c("col1", "col2", "col3"))
      

      【讨论】:

        【解决方案3】:

        使用基本 R 的一种方法是循环遍历我们想要使用 lapply 更改值的列,match 使用 input_2$colx 的值并获取相应的 coly 值。

        input_1[-1] <- lapply(input_1[-1], function(x) input_2$coly[match(x, input_2$colx)])
        
        input_1
        #  col1 col2 col3
        #1  ex1    1    2
        #2  ex2    2    5
        #3  ex3    3    6
        #4  ex4    4    4
        

        其实你可以不使用lapply,直接unlist的值和match

        input_1[-1] <- input_2$coly[match(unlist(input_1[-1]), input_2$colx)]
        

        【讨论】:

          猜你喜欢
          • 2018-11-29
          • 2017-01-05
          • 2015-08-20
          • 2018-05-14
          • 2018-07-04
          • 2018-05-01
          • 2020-12-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多