【问题标题】:Long to Wide with Non-Unique Key Combinations in RR 中具有非唯一键组合的长到宽
【发布时间】:2019-10-24 15:36:21
【问题描述】:

我正在尝试将数据集从长格式转换为宽格式。需要这样做才能输入另一个程序以进行分析。我的输入数据如下:

sdata <- data.frame(c(1,1,1,1,1,1,1,1,1,1,1,1,1),c(1,1,1,1,1,1,1,1,1,2,2,2,2),c("X1","A","B","C","D","X2","A","B","C","X1","A","B","C"),c(81,31,40,5,5,100,8,90,2,50,20,24,6))
col_headings <- c("Orig","Dest","Desc","Estimate")
names(sdata) <- col_headings

输入数据

根据上面 Orig-Dest-X1、Orig-Dest-X2 类别的独特组合,子类别仅从 A、B、C 到 A、B、C、D 到 A、B 等。我是试图获得所需的输出(在下面的 R 中重新创建的代码)以及所需输出的图像。

sdata_spread <- data.frame(c(1,1),c(1,2),c(81,50),c(31,20),c(40,24),c(5,6),c(5,NA),c(100,NA),c(8,NA),c(90,NA),c(2,NA))
col_headings <- c("Orig","Dest","X1",   "X1_A", "X1_B", "X1_C", "X1_D","X2",    "X2_A", "X2_B", "X2_C")
names(sdata_spread) <- col_headings

期望的输出

我尝试了以下方法:

sdata_spread <- sdata %>% spread(Desc,Estimate)

我得到的错误是:

Error: Each row of output must be identified by a unique combination of keys.
Keys are shared for 6 rows

我也尝试了这里给出的公认答案:Long to wide with no unique key 和这里:Long to wide format with several duplicates. Circumvent with unique combo of columns,但它没有得到我想要的输出。

任何见解都将不胜感激。

谢谢, 克里希南

【问题讨论】:

    标签: r


    【解决方案1】:

    一个选项是根据“X”作为“Desc”中的第一个字符的出现来创建一个分组变量,使用它通过pasteing 'Desc'的first元素来修改“Desc” ' 每个元素都基于case_when 中的条件并使用pivot_wider 重塑为宽格式(从tidyr_1.0.0 开始,spread/gather 已被弃用,取而代之的是pivot_wider/pivot_longer

    library(dplyr)
    library(tidyr)
    library(stringr)
    sdata %>%
      group_by(grp = cumsum(str_detect(Desc, '^X'))) %>% 
      mutate(Desc = case_when(row_number() > 1 ~ str_c(first(Desc), Desc, sep="_"),
                TRUE ~ as.character(Desc))) %>%
      ungroup %>% 
      select(-grp) %>% 
      pivot_wider(names_from = Desc, values_from = Estimate)
    # A tibble: 2 x 11
    #   Orig  Dest    X1  X1_A  X1_B  X1_C  X1_D    X2  X2_A  X2_B  X2_C
    #  <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
    #1     1     1    81    31    40     5     5   100     8    90     2
    #2     1     2    50    20    24     6    NA    NA    NA    NA    NA
    

    【讨论】:

    • 我发现对于上面由 akrun 提供的最后一行代码,使用 spread(Desc,Estimate) 而不是 pivot_wider 也可以。
    • @Krishnan。 spread/gather 被弃用,取而代之的是 pivot_wider/pivot_longer
    猜你喜欢
    • 2017-07-22
    • 2016-01-09
    • 2014-01-06
    • 1970-01-01
    • 1970-01-01
    • 2020-03-22
    • 1970-01-01
    • 2021-04-10
    • 2022-11-23
    相关资源
    最近更新 更多