Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

modify column names order when using pivot_wider()

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 = " ")

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading