【问题标题】:How to reshape three columns of a data table into a printed table [duplicate]如何将数据表的三列重塑为打印表[重复]
【发布时间】:2015-01-05 19:34:50
【问题描述】:

我想打印一个表,其中包含一列的行名和第二列的列名,以及第三列的表值。

这是数据表dt的内容。 heading为船首,shipSpdKt为船速和kts,V1为表值。

    heading shipSpdKt          V1
 1:       0         5  -4.3057799
 2:      30         5  -4.2452984
 3:      60         5  -5.6391077
 4:      90         5  -4.9353771
 5:     120         5  -4.3519821
 6:     150         5  -2.3346472
 7:     180         5  -1.6274207
 8:       0        10  -6.0007901
 9:      30        10  -6.7137480
10:      60        10  -6.9774241
11:      90        10  -5.7268767
12:     120        10  -3.9167585
13:     150        10  -1.8365736
14:     180        10  -1.1103727
15:       0        20  -6.4556379
16:      30        20  -7.3609538
17:      60        20 -11.3018260
18:      90        20  -7.7640429
19:     120        20  -4.7670283
20:     150        20  -1.7899857
21:     180        20  -0.9479594
22:       0        30  -4.2182927
23:      30        30  -5.8362999
24:      60        30  -8.9905834
25:      90        30  -7.2139764
26:     120        30  -5.1285415
27:     150        30  -2.2860508
28:     180        30  -0.8197407

我想要类似的东西

print(dt)

生成一个打印表格,显示 V1 在航向和船速值处的值。这是显示所需输出的部分表格。

           shipSpdKt    
heading            5             10          20          30
      0       -4.305         -6.000      -6.455      -4.218
     30       -4.245
     60       -5.639
     90       -4.935
    120       -4.351
    150       -2.334
    180       -1.627

这是我最初的尝试,但它没有生成所需的表格

reshape(dt,v.names='heading',idvar='shipSpdKt',timevar="heading",direction="wide")

输出是

   shipSpdKt       V1 heading.0 heading.30 heading.60 heading.90 heading.120 heading.150
1:         5 4.505957         0         30         60         90         120         150
2:        10 5.683579         0         30         60         90         120         150
3:        20 6.427269         0         30         60         90         120         150
4:        30 3.961622         0         30         60         90         120         150
   heading.180
1:         180
2:         180
3:         180
4:         180

【问题讨论】:

  • dcast.data.table(dt, heading~shipSpdKt, value.var='V1')

标签: r dataframe data.table reshape


【解决方案1】:

使用基础reshape函数:

reshape(dt, timevar = "shipSpdKt", idvar = "heading", direction = "wide")

使用reshape2 包:

reshape2::dcast(dt, heading ~ shipSpdKt, value.var = "V1")

使用tidyr 包:

tidyr::spread(dt, shipSpdKt, V1)

使用data.table 包:

data.table::dcast.data.table(dt, heading ~ shipSpdKt, value.var = "V1")

【讨论】:

    猜你喜欢
    • 2022-09-23
    • 2021-07-03
    • 2021-06-30
    • 1970-01-01
    • 1970-01-01
    • 2012-03-25
    • 2014-10-10
    相关资源
    最近更新 更多