将列逆透视或转置为行 R

时间:2020-12-30 20:35:36

标签: r

给定以下数据框:

dt <- data.frame("Year"=2020,
                 "Month"=c("Jan","Jan","Feb"),
                 "Location"=c("Store_1","Store_1","Store_2"),
                 "Apples"=c(100, 150, 120),
                 "Oranges"=c(50, 70, 50))

  Year Month Location Apples Oranges
1 2020   Jan  Store_1    100      50
2 2020   Jan  Store_1    150      70
3 2020   Feb  Store_2    120      50

我怎样才能把这个表变成下表,基本上是通过保持前三列并取消后两列。

  Year Month Location   Type Values
1 2020   Jan  Store_1  Apple    100
2 2020   Jan  Store_1  Apple    150
3 2020   Feb  Store_2  Apple    120
4 2020   Jan  Store_1 Orange     50
5 2020   Jan  Store_1 Orange     70
6 2020   Feb  Store_2 Orange     50

对此有任何提示或技巧吗?

1 个答案:

答案 0 :(得分:0)

我们可以使用 pivot_longer 中的 tidyr

library(dplyr)
library(tidyr)
dt %>%
    pivot_longer(cols = Apples:Oranges, names_to = 'Type',
         values_to = 'Values') %>% 
    arrange(Year, Type)

-输出

# A tibble: 6 x 5
#   Year Month Location Type    Values
#  <dbl> <chr> <chr>    <chr>    <dbl>
#1  2020 Jan   Store_1  Apples     100
#2  2020 Jan   Store_1  Apples     150
#3  2020 Feb   Store_2  Apples     120
#4  2020 Jan   Store_1  Oranges     50
#5  2020 Jan   Store_1  Oranges     70
#6  2020 Feb   Store_2  Oranges     50