如何在 R 中执行更长时间的数据透视?

How to execute pivot longer in R?

下面是示例数据,也是我第一次尝试这样做。所需的结果在底部。没有错误,但没有产生预期的结果。我的主要问题是...为了获得理想的结果,我应该在“cols”部分输入什么?

 periodyear3 <-c(2020,2020,2020,2020,2020,2020,2020,2020,2020,2020,2020,2020)
 month3<-c(1,2,3,4,5,6,1,2,3,4,5,6)
 indcode3<-c(624410,624410,624410,624410,624410,624410,72,72,72,72,72,72)
 employment3 <-c(25,25,26,27,28,29,85,86,87,88,89,90)
 wages3 <-c(10000,10001,10002,10003,10004,10005,12510,12515,12520,12520,16528,19874)

 pivotexample <- data.frame(periodyear3,month3,indcode3,employment3,wages3)

 indcomp <- pivotexample %>%
    dplyr::select("indcode3","periodyear3","month3","employment3") %>% 
    dplyr::ungroup() %>% 
    tidyr::pivot_longer(cols = periodyear3:employment3, names_to = "indcode", values_to ="employment")


periodyear3    month3    624410      72
    2020          1         25       85
    2020          2         25       86
    2020          3         26       87
    2020          4         27       88
    2020          5         28       89
    2020          6         29       90

我认为您正在努力做到 _wider,而不是 _longer。或许是这样:

tidyr::pivot_wider(pivotexample, c(periodyear3, month3), 
                   names_from="indcode3", values_from="employment3")
# # A tibble: 6 x 4
#   periodyear3 month3 `624410`  `72`
#         <dbl>  <dbl>    <dbl> <dbl>
# 1        2020      1       25    85
# 2        2020      2       25    86
# 3        2020      3       26    87
# 4        2020      4       27    88
# 5        2020      5       28    89
# 6        2020      6       29    90