首页 > 解决方案 > 重塑R中的多列

问题描述

我有以下数据:

df <- data.frame(
  wave = c(350, 352),
  cdom = c(0.164910664183534, 0.161336423973549),
  total = c(0.173292853508359, 0.164541380243188),
  wave_1 = c(350, 352),
  cdom_1 = c(0.157738707282744, 0.149555740098184),
  total_1 = c(0.16501632769282, 0.151631889636391),
  wave_2 = c(350, 352),
  cdom_2 = c(0.143293704793142, 0.133057094683334),
  total_2 = c(0.148878497119496, 0.136150629840465),
  wave_3 = c(350, 352),
  cdom_3 = c(0.0972284241775975, 0.0906890150335725),
  total_3 = c(0.108645612944463, 0.103640164204995),
  wave_4 = c(350, 352),
  cdom_4 = c(0.0801780489449968, 0.0779336395415438),
  total_4 = c(0.103930690374372, 0.095768602460239))

df
#>   wave      cdom     total wave_1    cdom_1   total_1 wave_2    cdom_2
#> 1  350 0.1649107 0.1732929    350 0.1577387 0.1650163    350 0.1432937
#> 2  352 0.1613364 0.1645414    352 0.1495557 0.1516319    352 0.1330571
#>     total_2 wave_3     cdom_3   total_3 wave_4     cdom_4   total_4
#> 1 0.1488785    350 0.09722842 0.1086456    350 0.08017805 0.1039307
#> 2 0.1361506    352 0.09068902 0.1036402    352 0.07793364 0.0957686

列代表 1 个样本。因此,在此示例中,有 5 个样本。我想用 4 列( 、 和 )将它改造成更长的dataframe形状。解决方案可以是基础 R,或者因为我没有任何偏好。samplewavecdomtotaldplyrdata.table

标签: rdplyrdata.table

解决方案


使用数据表:

library("data.table")

df <- data.table(df)
df[1, id := "a"]
df[2, id := "b"]
melt(df, id.vars = "id"  ,
     measure.vars = patterns(wave = "wave",
                             cdom = "cdom",
                             total = "total"))

    id variable wave       cdom     total
 1:  a        1  350 0.16491066 0.1732929
 2:  b        1  352 0.16133642 0.1645414
 3:  a        2  350 0.15773871 0.1650163
 4:  b        2  352 0.14955574 0.1516319
 5:  a        3  350 0.14329370 0.1488785
 6:  b        3  352 0.13305709 0.1361506
 7:  a        4  350 0.09722842 0.1086456
 8:  b        4  352 0.09068902 0.1036402
 9:  a        5  350 0.08017805 0.1039307
10:  b        5  352 0.07793364 0.0957686

推荐阅读