使用多个值的pivot_longer()对long进行整形

shstlldc  于 2023-04-09  发布在  其他
关注(0)|答案(2)|浏览(140)

我正在尝试对以下数据集进行长整型:

country  Data Type       Product   2007    [...]   2021
Austria  Retail Volume    id1      125             140
Austria  Retail Value     id1      15000           12000
Austria  Retail Volume    id2      75              25

我想重塑它(使用pivot_longer(),看在上帝的份上不要重塑),它有两个值_to,一个是零售量,一个是零售价值!我怎么做?

country  Product   Year    Retail Volume Retail Value   
Austria      id1      2007            
Austria      id1      2007         
Austria      id2      2007

问题是values_to必须是维度1!
我试了pivot_longer(),试了不同的帖子,没有帮助...

kqlmhetl

kqlmhetl1#

一个选项是执行pivot_longer,然后执行pivot_wider

library(tidyr)

dat |> 
  tidyr::pivot_longer(matches("\\d{4}")) |> 
  tidyr::pivot_wider(names_from = c(Data, Type), values_from = value)
#> # A tibble: 4 × 5
#>   country Product name  Retail_Volume Retail_Value
#>   <chr>   <chr>   <chr>         <int>        <int>
#> 1 Austria id1     2007            125        15000
#> 2 Austria id1     2021            140        12000
#> 3 Austria id2     2007             75           NA
#> 4 Austria id2     2021             25           NA

资料

dat <- read.table(text = "
country  Data Type       Product   2007    2021
Austria  Retail Volume    id1      125             140
Austria  Retail Value     id1      15000           12000
Austria  Retail Volume    id2      75              25           
", header = TRUE, check.names = FALSE)
jdgnovmf

jdgnovmf2#

看起来你必须先pivot_longer(),然后pivot_wider()

library(tidyverse)

df <- tribble(
  ~country, ~Data_Type, ~Product, ~`2007`, ~`2021`,
  "Austria", "Retail Volume", "id1", 125, 140,
  "Austria", "Retail Value", "id1", 15000, 12000,
  "Austria", "Retail Volume", "id2", 765, 25,
)

df  |> 
  pivot_longer(
    c(`2007`, `2021`),
    names_to = "year",
    values_to = "value"
  ) |> 
  pivot_wider(
    names_from = Data_Type,
    values_from = value
  )
#> # A tibble: 4 × 5
#>   country Product year  `Retail Volume` `Retail Value`
#>   <chr>   <chr>   <chr>           <dbl>          <dbl>
#> 1 Austria id1     2007              125          15000
#> 2 Austria id1     2021              140          12000
#> 3 Austria id2     2007              765             NA
#> 4 Austria id2     2021               25             NA

创建于2023-04-03带有reprex v2.0.2

相关问题