I'm struggling to find a way of changing column names order when pivoting them to wider. When doing a pivot, column name gets Val1 AA
, Val1 AB
order and I'd like to reverse it to have AB Val1
, AB Val1
etc. I didn't find a way to do it from pivot_wider package. I cannot use explicit column name values since they are dynamically changed. Thanks for any suggestions!
library(tidyverse)
Rank <- c('AA','AB','AC')
Val1 <- c(10,20,30)
Val2 <- c(40,50,60)
data <- data.frame(Rank,Val1, Val2)
data %>% pivot_wider(values_from = 2:3, names_from = Rank, names_sep = " ")
CodePudding user response:
You may use names_glue
instead
data %>% pivot_wider(values_from = 2:3, names_from = Rank, names_glue = "{Rank} {.value}")
`AA Val1` `AB Val1` `AC Val1` `AA Val2` `AB Val2` `AC Val2`
<dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
1 10 20 30 40 50 60