如何转置特定列值的数据框?

时间:2019-12-24 15:44:53

标签: r

我有如下数据框。

Country <- c("US","CA","UK","FR","US","CA","UK","FR","US","CA","UK","FR")

Month <- c(201901,201901,201901,201901,201902,201902,201902,201902,201903,201903,201903,201903)

HomeSales <- c(10,50,60,75,35,25,46,70,50,48,95,60)

CarSales <- c(10,50,60,75,35,25,46,70,50,48,95,60)

TransposeData <- data.frame(Country,Month,HomeSales,CarSales)

需要与以下相同的转置。

enter image description here

我的产品总是动态的,所以我需要构建代码来处理将来的产品。 请帮助我为我的数据集建立逻辑。预先感谢您的帮助。

1 个答案:

答案 0 :(得分:2)

使用pivot_longer从宽格式转换为长格式,然后使用arrange对其进行排序(如果需要排序)。

library(dplyr)
library(tidyr)

TransposeData %>%
  pivot_longer(3:4, names_to = "Product", values_to = "Sales") %>% 
  arrange(Product, Country, Month)

给予:

# A tibble: 24 x 4
   Country  Month Product  Sales
   <fct>    <dbl> <chr>    <dbl>
 1 CA      201901 CarSales    50
 2 CA      201902 CarSales    25
 3 CA      201903 CarSales    48
 4 FR      201901 CarSales    75
 5 FR      201902 CarSales    70
 6 FR      201903 CarSales    60
 7 UK      201901 CarSales    60
 8 UK      201902 CarSales    46
 9 UK      201903 CarSales    95
10 US      201901 CarSales    10
# ... with 14 more rows