如何在R中旋转数据框,使其转变为这种特定格式的另一个数据框?

时间:2018-08-26 10:28:02

标签: r dataframe pivot

我在R中有一个小的data frame,叫做df1

下面是data frame的样子:

SubDept2        BasicSalary     BenchmarkSalary
Admin             10000          20000
Bar                9880          12000
Entertainment     11960          17000
F&B                9680          12000
Finance           10310          17500
Housekeeping       9960          12000
Kitchen            9680          12000
Leisure & Sport   10775          17000
Maintenance       10240          10000
Restaurant         9880          12000
Rooms Division     9680          12000
Security          10250          11000
Spa                9450          12000

我想pivot这个data frame,以便原来是这样的:

SubDept2              Amount     Type
 Admin                10000      BasicSalary
 Bar                   9880      BasicSalary
 Entertainment        11960      BasicSalary
 F&B                   9680      BasicSalary
 Finance              10310      BasicSalary
 Housekeeping          9960      BasicSalary
 Kitchen               9680      BasicSalary
 Leisure & Sport      10775      BasicSalary
 Maintenance          10240      BasicSalary
 Restaurant            9880      BasicSalary
 Rooms Division        9680      BasicSalary
 Security             10250      BasicSalary
 Spa                   9450      BasicSalary
 Admin                20000      BenchmarkSalary
 Bar                  12000      BenchmarkSalary
 Entertainment        17000      BenchmarkSalary
 F&B                  12000      BenchmarkSalary
 Finance              17500      BenchmarkSalary
 Housekeeping         12000      BenchmarkSalary
 Kitchen              12000      BenchmarkSalary
 Leisure & Sport      17000      BenchmarkSalary
 Maintenance          10000      BenchmarkSalary
 Restaurant           12000      BenchmarkSalary
 Rooms Division       12000      BenchmarkSalary
 Security             11000      BenchmarkSalary
 Spa                  12000      BenchmarkSalary

这怎么办?

1 个答案:

答案 0 :(得分:-3)

library(tidyr)
df %>% gather(value='amount',key='Type',-SubDept2) %>% head(n=5)

       SubDept2        Type amount
1         Admin BasicSalary  10000
2           Bar BasicSalary   9880
3 Entertainment BasicSalary  11960
4           F&B BasicSalary   9680
5       Finance BasicSalary  10310