【发布时间】:2021-01-18 10:53:15
【问题描述】:
我正在尝试根据列名将数据从宽格式转换为长格式,这可以通过tidyr::pivot_longer() 轻松完成。但是,我还需要以宽格式解构特定单元格的内容——即解析其中的字符串——并沿着旋转(更长)行分离解析的组件。虽然使用stringr::separate_rows 可以轻松完成解析和分离任务,但我不知道如何在同一个镜头中结合旋转和分离过程。
数据
df <- data.frame(
id = 1:3,
blue_type1 = 110:112,
purple_type5 = 5:7,
black_type1 = 28:30,
batch_number = c("bgd | ddg | qwe",
"afp | qqw | edt",
"pqr | khp | rty")
)
df
## id blue_type1 purple_type5 black_type1 batch_number
## 1 1 110 5 28 bgd | ddg | qwe
## 2 2 111 6 29 afp | qqw | edt
## 3 3 112 7 30 pqr | khp | rty
我想要什么
转换为长格式并解压batch_number,这样第一个子字符串将分配给长格式的第一行,第二个子字符串分配给第二行,第三个子字符串分配给第三行。
期望的输出
## # A tibble: 9 x 5
## id batch_number color type vals
## <dbl> <chr> <chr> <dbl> <dbl>
## 1 1 bgd blue 1 110
## 2 1 ddg purple 5 5
## 3 1 qwe black 1 28
## 4 2 afp blue 1 111
## 5 2 qqw purple 5 6
## 6 2 edt black 1 29
## 7 3 pqr blue 1 112
## 8 3 khp purple 5 7
## 9 3 rty black 1 30
我的尝试
如果我只是tidyr::pivot_longer,我就成功了一半:
df %>%
pivot_longer(.,
-c(id, batch_number),
names_to = c("color", "type"),
names_pattern = "(.*)_type(.)",
values_to = "vals")
## # A tibble: 9 x 5
## id batch_number color type vals
## <int> <chr> <chr> <chr> <int>
## 1 1 bgd | ddg | qwe blue 1 110
## 2 1 bgd | ddg | qwe purple 5 5
## 3 1 bgd | ddg | qwe black 1 28
## 4 2 afp | qqw | edt blue 1 111
## 5 2 afp | qqw | edt purple 5 6
## 6 2 afp | qqw | edt black 1 29
## 7 3 pqr | khp | rty blue 1 112
## 8 3 pqr | khp | rty purple 5 7
## 9 3 pqr | khp | rty black 1 30
如果我尝试 stringr::separate_rows 在此之上,我会得到不想要的输出:
## # A tibble: 27 x 5
## # Groups: id [3]
## id batch_number color type vals
## <int> <chr> <chr> <chr> <int>
## 1 1 bgd blue 1 110
## 2 1 ddg blue 1 110
## 3 1 qwe blue 1 110
## 4 1 bgd purple 5 5
## 5 1 ddg purple 5 5
## 6 1 qwe purple 5 5
## 7 1 bgd black 1 28
## 8 1 ddg black 1 28
## 9 1 qwe black 1 28
## 10 2 afp blue 1 111
## 11 2 qqw blue 1 111
## 12 2 edt blue 1 111
## 13 2 afp purple 5 6
## 14 2 qqw purple 5 6
## 15 2 edt purple 5 6
## 16 2 afp black 1 29
## 17 2 qqw black 1 29
## 18 2 edt black 1 29
## 19 3 pqr blue 1 112
## 20 3 khp blue 1 112
## 21 3 rty blue 1 112
## 22 3 pqr purple 5 7
## 23 3 khp purple 5 7
## 24 3 rty purple 5 7
## 25 3 pqr black 1 30
## 26 3 khp black 1 30
## 27 3 rty black 1 30
如何在运行pivot_longer 的同时合并separate_rows 的操作?有没有一种优雅的方式来完成这样的任务?基本上我正在寻找tidyverse 解决方案,但也会对其他方法感到满意。
【问题讨论】: