简体   繁体   English

如何将表格从列布局传递到 R 中的行布局?

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

I have an R table on a column layout.我在列布局上有一个 R 表。 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.然后我为它们创建一个带有 id 的列。 Then I append them.然后我 append 他们。

But is there an shorter way to do this?但是有没有更短的方法来做到这一点?

Thanks in advance, Tables提前致谢,

Using tidyr and using some created data since I didn't want to get the data from your pictures:使用tidyr并使用一些创建的数据,因为我不想从您的图片中获取数据:

> 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 :使用reshape2的替代方法:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM