使用多列旋转更宽
Pivot wider with multiple columns
我有一个看起来像这样的数据集
df <- data.frame(Country = c("USA","USA","USA","UK","UK","UK"),
Measure = c("Revenue","Profit","emp","Revenue","Profit","emp"),
Year_19 = c("250000","100000","15","140000","25000","4"),
Year_20 = c("130000","44000","8","76000","13000","3"))
我想以最终数据显示的方式重新排列它
Year_19_Revenue Year_19_Profit Year_19_emp Year_20_Revenue Year_20_Profit Year_20_emp
USA 250000 100000 15 130000 44000 8
UK 140000 25000 4 76000 13000 3
无法理解该怎么做。有人可以帮忙吗?谢谢
我们可以在values_from
中指定多个列
library(dplyr)
library(tidyr)
df %>%
pivot_wider(names_from = Measure, values_from = c(Year_19, Year_20))
-输出
# A tibble: 2 x 7
# Country Year_19_Revenue Year_19_Profit Year_19_emp Year_20_Revenue Year_20_Profit Year_20_emp
# <chr> <chr> <chr> <chr> <chr> <chr> <chr>
#1 USA 250000 100000 15 130000 44000 8
#2 UK 140000 25000 4 76000 13000 3
基本 R 选项
reshape(
df,
direction = "wide",
idvar = "Country",
timevar = "Measure"
)
给予
Country Year_19.Revenue Year_20.Revenue Year_19.Profit Year_20.Profit
1 USA 250000 130000 100000 44000
4 UK 140000 76000 25000 13000
Year_19.emp Year_20.emp
1 15 8
4 4 3
data.table
选项 dcast
> dcast(setDT(df),Country~Measure,value.var = c("Year_19","Year_20"))
Country Year_19_Profit Year_19_Revenue Year_19_emp Year_20_Profit
1: UK 25000 140000 4 13000
2: USA 100000 250000 15 44000
Year_20_Revenue Year_20_emp
1: 76000 3
2: 130000 8
我有一个看起来像这样的数据集
df <- data.frame(Country = c("USA","USA","USA","UK","UK","UK"),
Measure = c("Revenue","Profit","emp","Revenue","Profit","emp"),
Year_19 = c("250000","100000","15","140000","25000","4"),
Year_20 = c("130000","44000","8","76000","13000","3"))
我想以最终数据显示的方式重新排列它
Year_19_Revenue Year_19_Profit Year_19_emp Year_20_Revenue Year_20_Profit Year_20_emp
USA 250000 100000 15 130000 44000 8
UK 140000 25000 4 76000 13000 3
无法理解该怎么做。有人可以帮忙吗?谢谢
我们可以在values_from
library(dplyr)
library(tidyr)
df %>%
pivot_wider(names_from = Measure, values_from = c(Year_19, Year_20))
-输出
# A tibble: 2 x 7
# Country Year_19_Revenue Year_19_Profit Year_19_emp Year_20_Revenue Year_20_Profit Year_20_emp
# <chr> <chr> <chr> <chr> <chr> <chr> <chr>
#1 USA 250000 100000 15 130000 44000 8
#2 UK 140000 25000 4 76000 13000 3
基本 R 选项
reshape(
df,
direction = "wide",
idvar = "Country",
timevar = "Measure"
)
给予
Country Year_19.Revenue Year_20.Revenue Year_19.Profit Year_20.Profit
1 USA 250000 130000 100000 44000
4 UK 140000 76000 25000 13000
Year_19.emp Year_20.emp
1 15 8
4 4 3
data.table
选项 dcast
> dcast(setDT(df),Country~Measure,value.var = c("Year_19","Year_20"))
Country Year_19_Profit Year_19_Revenue Year_19_emp Year_20_Profit
1: UK 25000 140000 4 13000
2: USA 100000 250000 15 44000
Year_20_Revenue Year_20_emp
1: 76000 3
2: 130000 8