在 R 中旋转更宽时如何将多列数据合并为一列

问题描述 投票:0回答:1

我有一个结构与此示例类似的数据集:

df <- data.frame(sample=c('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H'),
                 test_1=c(2, 1, 4, 3, 5, 2, 1, 4),
                 test_2=c(8, 3, 9, 6, 8, 10, 7, 7),
                 test_3=c(4, 3, 4, 5, 3, 4, 5, 4))
view(df)
    
sample test_1 test_2 test_3
 A       2      8       4
 B       1      3       3
 C       4      9       4
 D       3      6       5
 E       5      8       3
 F       2      10      4
 G       1      7       5
 H       4      7       4

我想重构我的数据,使列名称为样本值(A、B、C 等),行名称为 test_1、test_2 和 test_3。

为此,我尝试在 tidyverse 中使用更宽的数据透视,但我的列变成 test_1_A、test_1_B、test_1_C 等,数据集中只有 1 个未命名行。

df %>%
  pivot_wider(names_from = sample, values_from = 2:4)

如有任何帮助,我们将不胜感激,谢谢!

r dataframe pivot tidyverse tidyr
1个回答
0
投票

使用

data.table

data.table::transpose(df, make.names = "sample", keep.names = "test")

#     test A B C D E  F G H
# 1 test_1 2 1 4 3 5  2 1 4
# 2 test_2 8 3 9 6 8 10 7 7
# 3 test_3 4 3 4 5 3  4 5 4
© www.soinside.com 2019 - 2024. All rights reserved.