0

For example I have a data frame on the ratings of TV shows in three countries (12 tv shows in each country) as below.

Austria Belgium Canada
102.71  103.87  470.49
103.21  106.06  483.52
109.86  114.1   492.41
194.1   119.98  498.56
198.69  204.92  503.6
202.52  209.21  608.15
205.62  222.59  612.21
208.34  225.91  615.78
211.09  298.63  619.1
213.31  321.68  622.01
215.65  324.28  624.78
217.88  326.7   627.46

I want to transform this data frame into a two-column data frame: one column for ratings and one column for corresponding countries, for example:

Ratings Countries
102.71  Austria
103.21  Austria
....
103.87  Belgium
...

I tried package reshape but cannot get what I want. Thanks!

RandomThinker
  • 391
  • 1
  • 6

2 Answers2

1

I guess you can use stack

setNames(stack(df),c("Rating","Countries"))

which gives

  Rating Countries
1  102.71   Austria
2  103.21   Austria
3  109.86   Austria
4  194.10   Austria
5  198.69   Austria
6  202.52   Austria
7  205.62   Austria
8  208.34   Austria
9  211.09   Austria
10 213.31   Austria
11 215.65   Austria
12 217.88   Austria
13 103.87   Belgium
14 106.06   Belgium
15 114.10   Belgium
16 119.98   Belgium
17 204.92   Belgium
18 209.21   Belgium
19 222.59   Belgium
20 225.91   Belgium
21 298.63   Belgium
22 321.68   Belgium
23 324.28   Belgium
24 326.70   Belgium
25 470.49    Canada
26 483.52    Canada
27 492.41    Canada
28 498.56    Canada
29 503.60    Canada
30 608.15    Canada
31 612.21    Canada
32 615.78    Canada
33 619.10    Canada
34 622.01    Canada
35 624.78    Canada
36 627.46    Canada
ThomasIsCoding
  • 96,636
  • 9
  • 24
  • 81
1

tidyr provides the function pivot_longer (and also pivot_wider) for such pivoting tasks. The syntax makes quite clear what is going to happen.

library(tidyr)
pivot_longer(df, Austria:Canada, names_to = "Countries", values_to = "Ratings")
eastclintw00d
  • 2,250
  • 1
  • 9
  • 18