Search code examples
rlayoutline

How to pass a table from a column layout to a line layout in R?


I have an R table on a column layout. In the picture it's the left one. And I would like to put it on a line layout, it would look like the right table.

My idea is to create a table without the column net and a table without the ceded. I change the field's names net and ceded with amount. Then i create a column with the id for both of them. Then I append them.

But is there an shorter way to do this ?

Thanks in advance, Tables


Solution

  • Using tidyr and using some created data since I didn't want to get the data from your pictures:

    > data
      year      net    ceded
    1    1 266.73007 317.6823
    2    2 729.50176 366.0213
    3    3 425.06088 162.0960
    4    4 723.09221 348.2421
    5    5  45.05688 467.0686
    6    6  44.78075 154.3635
    7    7  59.73864 750.4060
    8    8 526.06015 585.1687
    9    9 229.78809 554.1722
    10  10 355.92545 232.5220
    

    Now we want to transform those data into a "longer" format:

    data %>%
      pivot_longer(cols=c(net, ceded), names_to="id", values_to="amount")
    

    yields

    # A tibble: 20 x 3
        year id    amount
       <int> <chr>  <dbl>
     1     1 net    267. 
     2     1 ceded  318. 
     3     2 net    730. 
     4     2 ceded  366. 
     5     3 net    425. 
     6     3 ceded  162. 
     7     4 net    723. 
     8     4 ceded  348. 
     9     5 net     45.1
    10     5 ceded  467. 
    11     6 net     44.8
    12     6 ceded  154. 
    13     7 net     59.7
    14     7 ceded  750. 
    15     8 net    526. 
    16     8 ceded  585. 
    17     9 net    230. 
    18     9 ceded  554. 
    19    10 net    356. 
    20    10 ceded  233. 
    

    An alternative using reshape2:

    data %>%
      melt(id.vars=c("year"), measure.vars=c("net", "ceded"))