如何在 R 中多次执行 pivot_wider?

How to execute a pivot_wider multiple times in R?

下面是样本数据和期望的结果。手头的任务是旋转多次(或者至少我认为是多次)以便为每行创建一个完整的历史系列。目前,每个 qtr(季度)是一行。命名约定并不是那么重要。我知道如何做 pivot_wider,但每月列名的创建让我很困惑。

 area <- c("000000","000000","000000","000000","000003","000003","000003","000003")
 indcode <- c("432100","432100","432100","432100","432100","432100","432100","432100")
 Year <- c("2019","2019","2019","2019","2019","2019","2019","2019")
 qtr <- c("01","02","03","04","01","02","03","04")
 month1_emplvl <-c(100,101,102,103,44,44,46,52)
 month2_emplvl <-c(100,101,103,104,48,44,52,41)
 month3_emplvl <-c(101,100,102,99,44,45,46,47)

 testdata <- data.frame(area,indcode,Year,qtr,month1_emplvl,month2_emplvl,month3_emplvl)

想要的结果

  area    indcode    2019-01     2019-02   2019-03    2019-04   2019-05   2019-06 and so on...
  000000    432100      100         100        101      101        101        100
  000003    432100       44          48         44       44        44          45











 

这是您正在寻找的解决方案吗(将所有月份传递给 values_from 参数)?

df <- pivot_wider(testdata, values_from = c(month1_emplvl, month2_emplvl, month3_emplvl), names_from = c(Year, qtr))

我不知道你想如何多次应用旋转,但我认为你可以使用

library(tidyr)
library(dplyr)
library(stringr)

testdata %>% 
  pivot_longer(starts_with("month"), names_pattern = "month(\d)_*") %>% 
  mutate(
    new_name = 
      paste(Year, 
            str_pad((as.integer(qtr) - 1) * 3 + as.integer(name), 
                    width = 2, 
                    side = "left", 
                    pad = "0"),
            sep = "-"),
    .keep = "unused") %>%   
  pivot_wider(names_from = new_name)

这个returns

# A tibble: 2 x 14
  area  indcode `2019-01` `2019-02` `2019-03` `2019-04` `2019-05` `2019-06` `2019-07` `2019-08`
  <chr> <chr>       <dbl>     <dbl>     <dbl>     <dbl>     <dbl>     <dbl>     <dbl>     <dbl>
1 0000~ 432100        100       100       101       101       101       100       102       103
2 0000~ 432100         44        48        44        44        44        45        46        52
# ... with 4 more variables: `2019-09` <dbl>, `2019-10` <dbl>, `2019-11` <dbl>,
#   `2019-12` <dbl>