转置 Dataframe

jk9hmnmh  于 2023-01-28  发布在  其他
关注(0)|答案(2)|浏览(94)

我有以下数据:

structure(list(Tempo = c("t0", "t1", "REC1", "REC2", "REC4", 
"REC8", "REC11"), sig_C = c("a", "a", "a", "a", "a", "a", "a"
), sig_C1 = c("a", "a", "a", "a", "a", "a", "a"), sig_C2 = c("a", 
"a", "a", "a", "a", "a", "a"), sig_C3 = c("a", "a", "a", "a", 
"a", "a", "a"), sig_C4 = c("a", "a", "a", "a", "a", "a", "a"), 
    sig_C5 = c("a", "b", "b", "ab", "ab", "ab", "a")), row.names = c(NA, 
-7L), class = c("tbl_df", "tbl", "data.frame"))

我想转置这个 Dataframe ,保留Tempo作为列名,保留sig_C直到sig_C5作为名为group的变量。
我尝试使用t()函数,但没有以预期的方式工作。
谢谢

nzrxty8p

nzrxty8p1#

也许可以使用类似下面的内容来润色t()结果:

library(dplyr)
library(tibble)

dft <- t(df)
colnames(dft) <- dft[1,]
as.data.frame.matrix(dft[-1,]) %>% 
  rownames_to_column("Group") %>% 
  as_tibble()
#> # A tibble: 6 × 8
#>   Group  t0    t1    REC1  REC2  REC4  REC8  REC11
#>   <chr>  <chr> <chr> <chr> <chr> <chr> <chr> <chr>
#> 1 sig_C  a     a     a     a     a     a     a    
#> 2 sig_C1 a     a     a     a     a     a     a    
#> 3 sig_C2 a     a     a     a     a     a     a    
#> 4 sig_C3 a     a     a     a     a     a     a    
#> 5 sig_C4 a     a     a     a     a     a     a    
#> 6 sig_C5 a     b     b     ab    ab    ab    a

输入:

df <- structure(list(
  Tempo = c(
    "t0", "t1", "REC1", "REC2", "REC4",
    "REC8", "REC11"
  ), sig_C = c("a", "a", "a", "a", "a", "a", "a"), sig_C1 = c("a", "a", "a", "a", "a", "a", "a"), sig_C2 = c(
    "a",
    "a", "a", "a", "a", "a", "a"
  ), sig_C3 = c(
    "a", "a", "a", "a",
    "a", "a", "a"
  ), sig_C4 = c("a", "a", "a", "a", "a", "a", "a"),
  sig_C5 = c("a", "b", "b", "ab", "ab", "ab", "a")
), row.names = c(
  NA,
  -7L
), class = c("tbl_df", "tbl", "data.frame"))

创建于2023年1月26日,使用reprex v2.0.2

myzjeezk

myzjeezk2#

您可以尝试使用tidyr库中的pivot()对其进行整形。

library(tidyr)

df_reshaped <- pivot(data = df, id_cols = Tempo, cols_to_rename = sig_C:sig_C5, values_to = "group")
After running this, you'll have the dataframe with Tempo as columns and sig_C to sig_C5 as variable called group.

相关问题