【问题标题】:Wide the tibble into row and creating new columns based on row using R将 tibble 扩展到行并使用 R 基于行创建新列
【发布时间】:2020-10-16 13:49:12
【问题描述】:

下图是数据集的表示。我尝试使用 reshape 和 pivot_wider 来扩大数据,但无法以我预期的方式获得结果。 我从堆栈溢出中尝试了Merging multiple rows into single row,但发现解决方案有误。

下图是我想要从数据集中得到的预期结果

随机数据集生成代码

df1 <- data.frame(Components = c(rep("ABC",5),rep("BCD",5)), 
              Size = c(sample(1:100,5),sample(45:100,5)),
              Age = c(sample(1:100,5),sample(45:100,5)))

【问题讨论】:

  • 使用set.seed() 使输入数据可重现。不要将输入数据显示为图像,而是显示控制台打印输出。
  • 亲爱的 sindri_baldur,我已经提到它是一个随机数据集。在我的解决方案中有任何价值是完全可以的。我想要的只是按预期加宽表格/小标题
  • 目的只是让那些帮助的人生活得更轻松。这些是一般的 StackOverflow 标准:stackoverflow.com/questions/5963269/…

标签: r tidyverse rows reshape2 tibble


【解决方案1】:

试试这个tidyverse 解决方案,它将产生接近你想要的输出。您可以按Components 分组,然后创建一个顺序 ID 来标识未来的列。之后重塑为长 (pivot_longer()) 将变量名称与 id 组合,然后重塑为宽 (pivot_wider())。这是我使用您共享的数据的代码:

library(tidyverse)
#Code
newdf <- df1 %>% group_by(Components) %>% mutate(id=row_number()) %>%
  pivot_longer(-c(Components,id)) %>%
  mutate(name=paste0(name,'.',id)) %>% select(-id) %>%
  pivot_wider(names_from = name,values_from=value)

输出:

# A tibble: 2 x 11
# Groups:   Components [2]
  Components Size.1 Age.1 Size.2 Age.2 Size.3 Age.3 Size.4 Age.4 Size.5 Age.5
  <fct>       <int> <int>  <int> <int>  <int> <int>  <int> <int>  <int> <int>
1 ABC            23    94     52    89     15    25     76    38     33    99
2 BCD            59    62     55    81     81    61     80    83     97    68

【讨论】:

    【解决方案2】:

    我们可以使用unite 来合并列,然后使用pivot_wider

    library(dplyr)
    library(tidyr)
    library(data.table)
    df1 %>%
       mutate(rn = rowid(Components)) %>%
       pivot_longer(cols = Size:Age) %>% 
       unite(name, name, rn, sep=".") %>%
       pivot_wider(names_from = name, values_from = value)
    

    -输出

    # A tibble: 2 x 11
    #  Components Size.1 Age.1 Size.2 Age.2 Size.3 Age.3 Size.4 Age.4 Size.5 Age.5
    #  <chr>       <int> <int>  <int> <int>  <int> <int>  <int> <int>  <int> <int>
    #1 ABC            11    16     79    57     70     2     80     6     91    24
    #2 BCD            67    81     63    77     48    73     52   100     49    76
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-09-13
      • 2014-04-28
      • 1970-01-01
      • 2019-09-06
      • 1970-01-01
      • 1970-01-01
      • 2018-10-15
      • 2015-08-01
      相关资源
      最近更新 更多