使用Tidyr扩展具有多个键或值的表

hts6caw3  于 2023-04-03  发布在  其他
关注(0)|答案(2)|浏览(96)

我想铺一张table。附上一张照片。我正试图用Tidyverse来做。
我的尝试是:

Want = Have |> spread(key = Group, value = Number)

结果很差,每次都有2行。替换键或尝试多个值都不起作用或以错误结束。它必须简单,如何才能做到?

zd287kbt

zd287kbt1#

library(tidyverse)

df <- tribble(
    ~Time, ~Group,   ~Name, ~Number,
        1,    "A",  "AKSJ",      12,
        1,    "B",   "ASJ",      13,
        2,    "A", "ISJKS",      12,
        2,    "B",   "EFJ",      45,
        3,    "A",    "IF",      12,
        3,    "B",    "DE",      54
)

df |> 
  pivot_wider(
    names_from = Group,
    values_from = c(Name, Number),
    names_vary = "slowest"
  ) 
#> # A tibble: 3 × 5
#>    Time Name_A Number_A Name_B Number_B
#>   <dbl> <chr>     <dbl> <chr>     <dbl>
#> 1     1 AKSJ         12 ASJ          13
#> 2     2 ISJKS        12 EFJ          45
#> 3     3 IF           12 DE           54

创建于2023-03-28带有reprex v2.0.2

zzlelutf

zzlelutf2#

对于基R,我们可以像下面这样尝试reshape来将表旋转得更宽

reshape(
  df,
  direction = "wide",
  idvar = "Time",
  timevar = "Group"
)

使得

Time Name.A Number.A Name.B Number.B
1    1   AKSJ       12    ASJ       13
3    2  ISJKS       12    EFJ       45
5    3     IF       12     DE       54

数据

> dput(df)
structure(list(Time = c(1, 1, 2, 2, 3, 3), Group = c("A", "B",
"A", "B", "A", "B"), Name = c("AKSJ", "ASJ", "ISJKS", "EFJ",
"IF", "DE"), Number = c(12, 13, 12, 45, 12, 54)), row.names = c(NA,
-6L), class = "data.frame")

相关问题