【问题标题】:Match data.table/data.frame with matrix that partially matches将 data.table/data.frame 与部分匹配的矩阵匹配
【发布时间】:2021-10-23 08:07:24
【问题描述】:

我正在尝试合并以下data.table:

DE <- structure(list(date1 = c("2000", "2001", "2003"), country = c("DE", 
"DE", "DE"), value = c(10, 20, 30)), row.names = c(NA, -3L), class = c("data.table", 
"data.frame"))

   date1 country value
1:  2000      DE    10
2:  2001      DE    20
3:  2003      DE    30 

我想将它与一个带有 0 的矩阵合并:

df <- structure(c(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0), .Dim = 6:5, .Dimnames = list(
    c("2000", "2001", "2002", "2003", "2004", "2005"), c("UK", 
    "DE", "FR", "SP", "IT")))

     UK DE FR SP IT
2000  0  0  0  0  0
2001  0  0  0  0  0
2002  0  0  0  0  0
2003  0  0  0  0  0
2004  0  0  0  0  0
2005  0  0  0  0  0

这样期望的输出如下:

     UK DE  FR SP IT
2000  0  10  0  0  0
2001  0  20  0  0  0
2002  0  0   0  0  0
2003  0  30  0  0  0
2004  0  0   0  0  0
2005  0  0   0  0  0

【问题讨论】:

  • 你也可以dcast data.table DE 让它看起来像你的矩阵。

标签: r merge data.table


【解决方案1】:

我们可以使用行/列索引将 'value' 列从 'DE' 分配给 'df'

df[DE$date1, DE$country] <- DE$value

-输出

> df
     UK DE FR SP IT
2000  0 10  0  0  0
2001  0 20  0  0  0
2002  0  0  0  0  0
2003  0 30  0  0  0
2004  0  0  0  0  0
2005  0  0  0  0  0

【讨论】:

    【解决方案2】:

    这与大师 akrun 的解决方案形成鲜明对比。很明显,这与他的解决方案无法相提并论。出于学习目的,我的想法:

    1. dfmatrix, array 类。所以把它带到dataframe 类,而不是tibble,因为小标题不接受行名。
    2. pivot_wider 并添加 right_join
    3. 然后做一些调整,mutate(DE = coalesce(DE.x,DE.y), .keep="unused", .before=4) 我真的很喜欢。
    4. 带回rownames
    library(dplyr)
    library(tidyr)
    
    df <- df %>% 
        as.data.frame() %>%  
        rownames_to_column("date1")
    
    DE %>% 
        pivot_wider(
        names_from = country,
        values_from = value
        ) %>% 
        right_join(df, by="date1") %>% 
        arrange(date1) %>% 
        mutate(DE = coalesce(DE.x,DE.y), .keep="unused", .before=4) %>% 
        column_to_rownames("date1")
    
         UK DE FR SP IT
    2000  0 10  0  0  0
    2001  0 20  0  0  0
    2002  0  0  0  0  0
    2003  0 30  0  0  0
    2004  0  0  0  0  0
    2005  0  0  0  0  0
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-04-12
      • 1970-01-01
      • 2020-09-24
      • 2012-06-10
      • 2016-07-27
      • 1970-01-01
      • 2018-01-21
      • 2014-08-12
      相关资源
      最近更新 更多