如何将数据 table 的三列重塑为打印的 table

How to reshape three columns of a data table into a printed table

我想打印一个 table,其中行名来自一列,列名来自第二列,table 值来自第三列。

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

    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)

生成打印的 table,显示航向和船速值的 V1 值。这是显示所需输出的部分 table。

           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

这是我的初步尝试,但没有达到预期效果 table

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

使用基础 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")