使用变量块旋转更长时间 [英] Pivot longer with blocks of variables

查看:0
本文介绍了使用变量块旋转更长时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在变量块上使用pivot_longer时遇到问题。假设我有这个:


我想要这个:

dfwide <- structure(list(date = structure(c(1577836800, 1577923200, 1578009600, 
1578096000, 1578182400, 1578268800), class = c("POSIXct", "POSIXt"
), tzone = "UTC"), x1_a = c(20, 15, 12, NA, 25, 27), x1_b = c(33, 
44, 85, 10, 12, 3), x1_c = c(70, 20, 87, 11, 20, 5), x2_a = c(85, 
65, 33, 46, 82, 9), x2_b = c(87, 25, 55, 64, 98, 5), x2_c = c(77, 
51, 92, 20, 37, 98)), row.names = c(NA, -6L), class = c("tbl_df", 
"tbl", "data.frame")) 

##Tried:
dfwide %>% 
  pivot_longer(cols = -date,
             names_sep = c("x1", "x2"),
             names_to = c("a", "b", "c"),
             values_to = "value")

推荐答案

该行正在利用pivot_longer函数的名称分隔选项。

pivot_longer(dfwide, -date, names_sep = "_", 
             names_to=c("which", ".value")) %>% 
   arrange(which)


    # A tibble: 12 x 5
   date                which     a     b     c
   <dttm>              <chr> <dbl> <dbl> <dbl>
 1 2020-01-01 00:00:00 x1       20    33    70
 2 2020-01-02 00:00:00 x1       15    44    20
 3 2020-01-03 00:00:00 x1       12    85    87
 4 2020-01-04 00:00:00 x1       NA    10    11
 5 2020-01-05 00:00:00 x1       25    12    20
 6 2020-01-06 00:00:00 x1       27     3     5
 7 2020-01-01 00:00:00 x2       85    87    77
 8 2020-01-02 00:00:00 x2       65    25    51
 9 2020-01-03 00:00:00 x2       33    55    92
10 2020-01-04 00:00:00 x2       46    64    20
11 2020-01-05 00:00:00 x2       82    98    37
12 2020-01-06 00:00:00 x2        9     5    98

这篇关于使用变量块旋转更长时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆