R语言 优雅的方式来整理数据与两个级别的头,保留两个头在高格式

vfhzx4xs  于 2023-07-31  发布在  其他
关注(0)|答案(1)|浏览(86)

online tutorial说明了tidyr的gather函数:
gather()收集一组列名并将它们放入单个“key”列中。
但是,我想要两个键列,因为我被赋予了两个层次的标题数据。一个最小的工作示例是:

top_heads <- c(rep("Group1", 3), rep("Group2", 3))
bottom_heads <- c(rep(c("low", "medium", "high"),2))
values <-  matrix(rep(1:5, 6), ncol = 6)
table <- rbind(top_heads, bottom_heads, values)
print(table)
         [,1]     [,2]     [,3]     [,4]     [,5]     [,6]    
top_heads    "Group1" "Group1" "Group1" "Group2" "Group2" "Group2"
bottom_heads "low"    "medium" "high"   "low"    "medium" "high"  
              "1"      "1"      "1"      "1"      "1"      "1"     
              "2"      "2"      "2"      "2"      "2"      "2"     
              "3"      "3"      "3"      "3"      "3"      "3"     
              "4"      "4"      "4"      "4"      "4"      "4"     
              "5"      "5"      "5"      "5"      "5"      "5"

字符串
我想整理这些数据,使用gather或类似的函数,将标题和副标题分别保留在各自的列中。因此,它看起来像:

Group   Range Value
Group1  low    1
Group1  low    2


等等。
我可以猫的头,转换为数据框,转换值为数字,运行收集,然后拆分头(现在的关键字)。有没有更好的解决方案?

tf7tbtn2

tf7tbtn21#

library(tidyverse)

table %>%
  t() %>%
  as_tibble() %>%
  pivot_longer(-ends_with("heads")) %>%
  transmute(Group = top_heads, Range = bottom_heads, Value = as.numeric(value))

字符串
感谢akrun提出t()的想法

相关问题