【问题标题】:Comparing two dataframes in R and extract the values from one dataframe比较 R 中的两个数据帧并从一个数据帧中提取值
【发布时间】:2020-07-21 14:34:36
【问题描述】:

我有两个具有不同行数和列数的数据框。一个数据框有两列,另一个数据框有多列。 第一个数据帧看起来像,

第二个数据框是这样的

实际上,我需要将包含 A、B、C 等的第二个数据帧替换为第一个数据帧的第二列的值。

我需要以下格式的输出。

帮我解决这个问题。

输入:

df

structure(list(col1 = c("A", "B", "C", "D", "E", "F", "G", "H", 
"I", "J", "K", "L"), col2 = c(10, 1, 2, 3, 4, 3, 1, 8, 19, 200, 
12, 112)), row.names = c(NA, -12L), class = c("tbl_df", "tbl", 
"data.frame"))

df2

structure(list(col1 = c("A", "F", "W", "E", "F", "G"), col2 = c(NA, 
NA, "J", "K", "L", NA), col3 = c(NA, "H", "I", NA, "A", "B")), row.names = c(NA, 
-6L), class = c("tbl_df", "tbl", "data.frame"))

【问题讨论】:

  • 请将您的数据框编码到问题中

标签: r dataframe match


【解决方案1】:

单行:

as_tibble(`colnames<-`(matrix(df1$col2[match(as.matrix(df2),df1$col1)], ncol=3), names(df2)))
#> # A tibble: 6 x 3
#>    col1  col2  col3
#>   <dbl> <dbl> <dbl>
#> 1    10    NA    NA
#> 2     3    NA     8
#> 3    NA   200    19
#> 4     4    12    NA
#> 5     3   112    10
#> 6     1    NA     1

【讨论】:

    【解决方案2】:

    您可以通过一些数据操作来完成此操作。将df2中的数据拉长,然后加入df,再将数据拉宽。

    rowid_to_column 是从长期工作过渡到广泛工作所必需的。您可以通过在链末尾添加 select(-rowid) 轻松删除该列。

    library(tidyverse)
    
    df2 %>%
        rowid_to_column() %>%
        pivot_longer(cols = -rowid) %>%
        left_join(df, by = c("value" = "col1")) %>%
        select(-value) %>%
        pivot_wider(names_from = name, values_from = col2)
    
    #   rowid  col1  col2  col3
    #   <int> <dbl> <dbl> <dbl>
    # 1     1    10    NA    NA
    # 2     2     3    NA     8
    # 3     3    NA   200    19
    # 4     4     4    12    NA
    # 5     5     3   112    10
    # 6     6     1    NA     1
    

    【讨论】:

      【解决方案3】:

      基础 R 中的单行代码:

      df2 <- as.data.frame(lapply(df2, function(x) ifelse(!is.na(x), setNames(df$col2, df$col1)[x], NA)))
      

      输出

      > df2
        col1 col2 col3
      1   10   NA   NA
      2    3   NA    8
      3   NA  200   19
      4    4   12   NA
      5    3  112   10
      6    1   NA    1
      

      【讨论】:

        【解决方案4】:

        base 中的另一个短衬里。您可以使用match 并将结果分配给df2[]

        df2[] <- df[match(unlist(df2), df[,1]), 2]
        df2
        #  col1 col2 col3
        #1   10   NA   NA
        #2    3   NA    8
        #3   NA  200   19
        #4    4   12   NA
        #5    3  112   10
        #6    1   NA    1
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2017-04-26
          • 1970-01-01
          • 2019-06-23
          • 1970-01-01
          • 1970-01-01
          • 2021-09-16
          相关资源
          最近更新 更多