Search code examples
rdataframefunctiondplyrtidyverse

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?

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