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

Wide format data by pasting two sets of variables into one in R

I’ve tried to wide-format my DATA into my Desired_output using:

pivot_wider(DATA, names_from = Year, values_from = c(Type, Language))

without success. Is there a way to achieve my Desired_output?

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

library(tidyverse)

DATA <- read.table(header=TRUE, text="
ID District       Type Year Language
1 GreshamBarlow   5F  1617   Spanish
1 GreshamBarlow   5F  1718   Spanish
2 JeffersonCounty 5F  1617   English
2 JeffersonCounty 5F  1718   English")


Desired_output <- read.table(header=TRUE, text="
ID District        1617             1718 
1  GreshamBarlow   5F_Spanish       5F_Spanish
2  JeffersonCounty 5F_English       5F_English")

>Solution :

DATA %>% 
   unite(Type, Type, Language) %>% 
   pivot_wider(names_from = Year, values_from = Type)

# A tibble: 2 × 4
     ID District        `1617`     `1718`    
  <int> <chr>           <chr>      <chr>     
1     1 GreshamBarlow   5F_Spanish 5F_Spanish
2     2 JeffersonCounty 5F_English 5F_English
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