Currently, I always do a combination of pivot_longer and pivot_wider, but I was hoping that I can directly get this result by pivoting_longer without doing the intermediate step:library(tidyverse)dat_long <- dat %>% pivot_longer(cols = starts_with("Q1")) %>% separate(name, into = c("item", "brand"), remove = FALSE)dat_wide <- dat_long %>% pivot_wider(id_cols = c(id, brand), names_from = item, values_from = value)在当前的示例中,执行此中间步骤仍然可以,但在其他不太干净的示例中会变得令人厌烦,例如假设我的列没有以 Q1r1_c1, Q1r1_c2, Q1r2_c1, Q1r2_c2 的良好结构命名,而是 Q4, Q5, Q8r1, Q8r2 地图所在的位置分别在 Q4 和 Q8r1 之间,以及 Q5/Q8r2 之间.With this current example it's still ok to do this intermediate step, but it gets tiresome in other less clean examples, e.g. suppose my columns weren't named in a nice structure with Q1r1_c1, Q1r1_c2, Q1r2_c1, Q1r2_c2, but instead would be Q4, Q5, Q8r1, Q8r2 where the map would be between Q4 and Q8r1, and Q5/Q8r2, respectively.推荐答案您可以使用:tidyr::pivot_longer(dat, cols = -id, names_to = c('.value', 'brand'), names_sep = "_")# id brand Q1r1 Q1r2# <chr> <chr> <dbl> <dbl>#1 A pepsi 1 1#2 A cola 0 0#3 B pepsi 0 1#4 B cola 0 1#5 C pepsi 1 1#6 C cola 1 1 这篇关于tidyverse pivot_longer 几组列,但避免中间 mutate_wider 步骤的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 1403页,肝出来的.. 09-08 09:32