【问题标题】:Data rectangling? - How do I reshape/collapse multiple rows of data based on a unique identifier into one cell in R?数据整理? - 如何根据唯一标识符将多行数据重塑/折叠到 R 中的一个单元格中?
【发布时间】:2018-06-06 18:58:52
【问题描述】:

我希望获取多行数据并将它们折叠到每个唯一标识符的一个单元格中。我正在使用一个相当混乱、大小合适的数据框,但我正在尝试完成的一个非常简单的示例如下:

mydf = data_frame(x=c(rep("A",3),rep("B",3),rep("C",3)),
                  y=letters[1:9])

mydf
# A tibble: 9 x 2
  x     y    
  <chr> <chr>
1 A     a    
2 A     b    
3 A     c    
4 B     d    
5 B     e    
6 B     f    
7 B     g    
8 B     h    
9 B     i  

我想运行一些代码...理想情况下通过使用tidyversemydf %&gt;% mutate(y = I'm really not sure, maybe one of the map functions) 然后最终的数据框看起来像这样:

better = data_frame(x=c("A","B","C"),
                    y=list(c(letters[1:3]),c(letters[4:6]),c(letters[7:9])))
better
# A tibble: 3 x 2
  x     y        
  <chr> <list>   
1 A     <chr [3]>
2 B     <chr [4]>
3 C     <chr [3]>

better$y
[[1]]
[1] "a" "b" "c"

[[2]]
[1] "d" "e" "f"

[[3]]
[1] "g" "h" "i"

如前所述,我的数据更大、更混乱,希望最终会出现在 Shiny 应用程序中,因此它需要完全自主,因此需要对可用的功能有充分的了解才能使其工作。我想它可能需要比mutate 更多的步骤,可能会创建一个类似于better 的单独数据框,然后将left_join 恢复为原始数据框。

谢谢!

【问题讨论】:

    标签: r reshape tidyr


    【解决方案1】:

    我们需要一个 summarise 分组,我们将“y”包装在 list

    out <- mydf %>%
            group_by(x) %>% 
            summarise(y = list(y))
    # A tibble: 3 x 2
    #  x     y        
    #  <chr> <list>   
    #1 A     <chr [3]>
    #2 B     <chr [3]>
    #3 C     <chr [3]>
    
    out$y
    #[[1]]
    #[1] "a" "b" "c"
    
    #[[2]]
    #[1] "d" "e" "f"
    
    #[[3]]
    #[1] "g" "h" "i"
    

    【讨论】:

    • 如此简单!出于某种原因,我从没想过将summarise 用于任何其他定量摘要......
    【解决方案2】:

    使用 tidyr 的嵌套函数。

    library(tidyverse)
    mydf %>% nest(-x)
    # A tibble: 3 x 2
      x    data            
      <chr> <list>          
    1 A     <tibble [3 x 1]>
    2 B     <tibble [3 x 1]>
    3 C     <tibble [3 x 1]>
    

    【讨论】:

      猜你喜欢
      • 2017-11-14
      • 1970-01-01
      • 2019-06-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-14
      • 2023-03-19
      相关资源
      最近更新 更多