0

I would like to print a table that has the row names from one column and the column names from a second column, and the table values from a third column.

Here's the contents of data table dt. The heading is the ship heading, shipSpdKt is the ship speed and kts, and V1 is the table value.

    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

I want something like

print(dt)

to produce a printed table showing the value of V1 at the heading and ship speed values. Here is a partial table showing the desired output.

           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

This is my initial attempt, but it doesn't produce the desired table

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

The output is

   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
David Arenburg
  • 91,361
  • 17
  • 137
  • 196

1 Answers1

1

Using the base reshape function:

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

Using the reshape2 package:

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

Using the tidyr package:

tidyr::spread(dt, shipSpdKt, V1)

Using the data.table package:

data.table::dcast.data.table(dt, heading ~ shipSpdKt, value.var = "V1")
nacnudus
  • 6,328
  • 5
  • 33
  • 47