Search code examples
r

How can I make my enormous dataframe from wide to long in R?


I have an absolutely enormous dataframe that I want to use most of the variables from. How can I easily make all of it go from wide to long? It seems pretty straightforward when you only really have one variable at different times, but I have quite a few variables (such as test scores in math year by year, as well as test scores in reading year by year, as well as attendance information year by year) and would like to somehow all at once make it so those are narrowed down to the ID, grade/year, and then separate columns for things like math scores, reading scores, and attendance. My goal is to do fixed effects, which isn't possible with the wide dataframe or with the narrow specifications that I've been able to elongate it to.

I want to have columns that say "math test scores" "reading test scores" etc which have the values of the results and one single column with the grade those were in, so that gk3treadss (reading score from 3rd grade) and gk2treadss (for 2nd grade) are in the same column, with separate columns denoting that student id (already in the dataset) and the grade.

I've used pivot_longer and it's worked for one column at a time, but tried to make it happen for multiple or use "unite" or "join" and it hasn't worked.

I've also used reshape but it won't separate things out properly.

There are 342 variables:

    structure(list(stdntid = structure(10000, label = "STUDENT ID", format.spss = "F5.0"), 
    gender = structure(1, label = "STUDENT GENDER", format.spss = "F1.0", labels = c(MALE = 1, 
    FEMALE = 2), class = c("haven_labelled", "vctrs_vctr", "double"
    )), race = structure(1, label = "STUDENT RACE/ETHNICITY", format.spss = "F1.0", labels = c(WHITE = 1, 
    BLACK = 2, ASIAN = 3, HISPANIC = 4, `NATIVE AMERICAN` = 5, 
    OTHER = 6), class = c("haven_labelled", "vctrs_vctr", "double"
    )), birthmonth = structure(1, label = "STUDENT MONTH OF BIRTH", format.spss = "F2.0", labels = c(JANUARY = 1, 
    FEBRUARY = 2, MARCH = 3, ARPIL = 4, MAY = 5, JUNE = 6, JULY = 7, 
    AUGUST = 8, SEPTEMBER = 9, OCTOBER = 10, NOVEMBER = 11, DECEMBER = 12
    ), class = c("haven_labelled", "vctrs_vctr", "double")), 
    birthday = structure(22, label = "STUDENT DAY OF BIRTH", format.spss = "F2.0"), 
    birthyear = structure(1979, label = "STUDENT YEAR OF BIRTH", format.spss = "F4.0"), 
    FLAGSGK = structure(0, label = "IN STAR IN KINDERGARTEN", format.spss = "F1.0", display_width = 10L, labels = c(NO = 0, 
    YES = 1), class = c("haven_labelled", "vctrs_vctr", "double"
    )), FLAGSG1 = structure(1, label = "IN STAR IN GRADE 1", format.spss = "F1.0", display_width = 10L, labels = c(NO = 0, 
    YES = 1), class = c("haven_labelled", "vctrs_vctr", "double"
    )), FLAGSG2 = structure(1, label = "IN STAR IN GRADE 2", format.spss = "F1.0", display_width = 10L, labels = c(NO = 0, 
    YES = 1), class = c("haven_labelled", "vctrs_vctr", "double"
    )), FLAGSG3 = structure(1, label = "IN STAR IN GRADE 3", format.spss = "F1.0", display_width = 10L, labels = c(NO = 0, 
    YES = 1), class = c("haven_labelled", "vctrs_vctr", "double"
    )), flaggk = structure(0, label = "ACHIEVEMENT DATA AVAILABLE GRADE K", format.spss = "F8.0", labels = c(NO = 0, 
    YES = 1), class = c("haven_labelled", "vctrs_vctr", "double"
    )), flagg1 = structure(1, label = "ACHIEVEMENT DATA AVAILABLE GRADE 1", format.spss = "F8.0", labels = c(NO = 0, 
    YES = 1), class = c("haven_labelled", "vctrs_vctr", "double"
    )), flagg2 = structure(1, label = "ACHIEVEMENT DATA AVAILABLE GRADE 2", format.spss = "F8.0", labels = c(NO = 0, 
    YES = 1), class = c("haven_labelled", "vctrs_vctr", "double"
    )), flagg3 = structure(1, label = "ACHIEVEMENT DATA AVAILABLE GRADE 3", format.spss = "F8.0", labels = c(NO = 0, 
    YES = 1), class = c("haven_labelled", "vctrs_vctr", "double"
    )), flagg4 = structure(1, label = "ACHIEVEMENT DATA AVAILABLE GRADE 4", format.spss = "F1.0", display_width = 10L, labels = c(NO = 0, 
    YES = 1), class = c("haven_labelled", "vctrs_vctr", "double"
    )), flagg5 = structure(1, label = "ACHIEVEMENT DATA AVAILABLE GRADE 5", format.spss = "F1.0", display_width = 10L, labels = c(NO = 0, 
    YES = 1), class = c("haven_labelled", "vctrs_vctr", "double"
    )), flagg6 = structure(0, label = "ACHIEVEMENT DATA AVAILABLE GRADE 6", format.spss = "F1.0", display_width = 10L, labels = c(NO = 0, 
    YES = 1), class = c("haven_labelled", "vctrs_vctr", "double"
    )), flagg7 = structure(0, label = "ACHIEVEMENT DATA AVAILABLE GRADE 7", format.spss = "F1.0", display_width = 10L, labels = c(NO = 0, 
    YES = 1), class = c("haven_labelled", "vctrs_vctr", "double"
    )), flagg8 = structure(0, label = "ACHIEVEMENT DATA AVAILABLE GRADE 8", format.spss = "F1.0", display_width = 10L, labels = c(NO = 0, 
    YES = 1), class = c("haven_labelled", "vctrs_vctr", "double"
    )), flagprt4 = structure(1, label = "IN PARTICIPATION STUDY GRADE 4", format.spss = "F1.0", display_width = 10L, labels = c(NO = 0, 
    YES = 1), class = c("haven_labelled", "vctrs_vctr", "double"
    )), flagidn8 = structure(0, label = "IN IDENTIFICATION STUDY GRADE 8", format.spss = "F1.0", display_width = 11L, labels = c(NO = 0, 
    YES = 1), class = c("haven_labelled", "vctrs_vctr", "double"
    )), flagprt8 = structure(0, label = "IN PARTICIPATION STUDY GRADE 8", format.spss = "F1.0", display_width = 10L, labels = c(NO = 0, 
    YES = 1), class = c("haven_labelled", "vctrs_vctr", "double"
    )), flagsatact = structure(0, label = "VALID SAT/ACT SCORE AVAILABLE", format.spss = "F1.0", display_width = 7L, labels = c(NO = 0, 
    YES = 1), class = c("haven_labelled", "vctrs_vctr", "double"
    )), flaghscourse = structure(0, label = "AT LEAST ONE YEAR OF HIGH SCHOOL COURSE DATA AVAILABLE", format.spss = "F1.0", display_width = 11L, labels = c(NO = 0, 
    YES = 1, MISSING = 9), class = c("haven_labelled", "vctrs_vctr", 
    "double")), flaghsgraduate = structure(0, label = "DATA ON HIGH SCHOOL GRADUATION STATUS AVAILABLE", format.spss = "F1.0", labels = c(NO = 0, 
    YES = 1), class = c("haven_labelled", "vctrs_vctr", "double"
    )), gkclasstype = structure(NA_real_, label = "CLASSROOM TYPE KINDERGARTEN", format.spss = "F1.0", labels = c(`SMALL CLASS` = 1, 
    `REGULAR CLASS` = 2, `REGULAR + AIDE CLASS` = 3), class = c("haven_labelled", 
    "vctrs_vctr", "double")), g1classtype = structure(3, label = "CLASSROOM TYPE GRADE 1", format.spss = "F1.0", labels = c(`SMALL CLASS` = 1, 
    `REGULAR CLASS` = 2, `REGULAR + AIDE CLASS` = 3), class = c("haven_labelled", 
    "vctrs_vctr", "double")), g2classtype = structure(3, label = "CLASSROOM TYPE GRADE 2", format.spss = "F1.0", labels = c(`SMALL CLASS` = 1, 
    `REGULAR CLASS` = 2, `REGULAR + AIDE CLASS` = 3), class = c("haven_labelled", 
    "vctrs_vctr", "double")), g3classtype = structure(3, label = "CLASSROOM TYPE GRADE 3", format.spss = "F1.0", labels = c(`SMALL CLASS` = 1, 
    `REGULAR CLASS` = 2, `REGULAR + AIDE CLASS` = 3), class = c("haven_labelled", 
    "vctrs_vctr", "double")), cmpstype = structure(3, label = "CLASS TYPE COMPOSITE", format.spss = "F1.0", labels = c(SMALL = 1, 
    REGULAR = 2, AIDE = 3), class = c("haven_labelled", "vctrs_vctr", 
    "double")), cmpsdura = structure(3, label = "DURATION COMPOSITE", format.spss = "F1.0", display_width = 5L), 
    yearsstar = structure(3, label = "NUMBER OF YEARS IN STAR", format.spss = "F5.0", display_width = 10L), 
    yearssmall = structure(0, label = "NUMBER OF YEARS IN SMALL CLASSES", format.spss = "F5.0", display_width = 10L), 
    gkschid = structure(NA_real_, label = "KINDERGARTEN SCHOOL ID", format.spss = "F6.0"), 
    gksurban = structure(NA_real_, label = "SCHOOL URBANICITY KINDERGARTEN", format.spss = "F1.0", labels = c(`INNER CITY` = 1, 
    SUBURBAN = 2, RURAL = 3, URBAN = 4), class = c("haven_labelled", 
    "vctrs_vctr", "double")), gktchid = structure(NA_real_, label = "KINDERGARTEN TEACHER ID", format.spss = "F8.0"), 
    gktgen = structure(NA_real_, label = "TEACHER GENDER KINDERGARTEN", format.spss = "F1.0", labels = c(MALE = 1, 
    FEMALE = 2), class = c("haven_labelled", "vctrs_vctr", "double"
    )), gktrace = structure(NA_real_, label = "TEACHER RACE/ETHNICITY KINDERGARTEN", format.spss = "F1.0", labels = c(WHITE = 1, 
    BLACK = 2, ASIAN = 3, HISPANIC = 4, `NATIVE AMERICAN` = 5, 
    OTHER = 6), class = c("haven_labelled", "vctrs_vctr", "double"
    )), gkthighdegree = structure(NA_real_, label = "TEACHER HIGHEST DEGREE KINDERGARTEN", format.spss = "F1.0", labels = c(ASSOCIATES = 1, 
    BACHELORS = 2, MASTERS = 3, `MASTERS +` = 4, SPECIALIST = 5, 
    DOCTORAL = 6), class = c("haven_labelled", "vctrs_vctr", 
    "double")), gktcareer = structure(NA_real_, label = "TEACHER CAREER LADDER LEVEL KINDERGARTEN", format.spss = "F1.0", labels = c(`CHOSE NO TO BE ON CAREER LADDER` = 1, 
    APPRENTICE = 2, PROBATION = 3, `LADDER LEVEL 1` = 4, `LADDER LEVEL 2` = 5, 
    `LADDER LEVEL 3` = 6, PENDING = 7), class = c("haven_labelled", 
    "vctrs_vctr", "double")), gktyears = structure(NA_real_, label = "YEARS OF TOTAL TEACHING EXPERIENCE KINDERGARTEN", format.spss = "F2.0"), 
    gkclasssize = structure(NA_real_, label = "CLASS SIZE KINDERGARTEN", format.spss = "F5.0", display_width = 11L), 
    gkfreelunch = structure(NA_real_, label = "FREE/REDUCED LUNCH STATUS KINDERGARTEN", format.spss = "F1.0", labels = c(`FREE LUNCH` = 1, 
    `NON-FREE LUNCH` = 2), class = c("haven_labelled", "vctrs_vctr", 
    "double")), gkrepeat = structure(NA_real_, label = "REPEATING KINDERGARTEN IN 1985-1986 SCHOOL YEAR", format.spss = "F1.0", labels = c(`YES, PROMOTION RECOMMENDED` = 1, 
    `NO, PROMOTION NOT RECOMMENDED` = 2), class = c("haven_labelled", 
    "vctrs_vctr", "double")), gkspeced = structure(NA_real_, label = "SPECIAL EDUCATION STATUS KINDERGARTEN", format.spss = "F1.0", labels = c(YES = 1, 
    NO = 2), class = c("haven_labelled", "vctrs_vctr", "double"
    )), gkspecin = structure(NA_real_, label = "PULLED OUT FOR SPECIAL INSTRUCTION KINDERGARTEN", format.spss = "F1.0", labels = c(YES = 1, 
    NO = 2), class = c("haven_labelled", "vctrs_vctr", "double"
    )), gkpresent = structure(NA_real_, label = "DAYS PRESENT AT SCHOOL KINDERGARTEN", format.spss = "F5.0"), 
    gkabsent = structure(NA_real_, label = "DAYS ABSENT FROM SCHOOL KINDERGARTEN", format.spss = "F5.0"), 
    gktreadss = structure(NA_real_, label = "TOTAL READING SCALE SCORE SAT KINDERGARTEN", format.spss = "F5.0"), 
    gktmathss = structure(NA_real_, label = "TOTAL MATH SCALE SCORE SAT KINDERGARTEN", format.spss = "F5.0")), row.names = c(NA, 
-1L), class = c("tbl_df", "tbl", "data.frame"))

Here is an example of the data right now:

ID Gender gktreadss g1treadss g2treadss gktmathss g1tmathss g2tmathss gktrace g1trace g2trace
1231 1 500 506 590 600 NA NA 1 2 1
1232 2 533 533 690 655 667 700 2 1 1
1233 2 616 668 789 655 556 688 1 1 1
1234 1 599 677 555 665 688 789 1 2 1
library(tidyverse)
d <- tibble(
  ID = c(1231, 1232, 1233, 1234),
  Gender = c(1, 2, 2, 1),
  gktreadss = c(500, 533, 616, 599),
  g1treadss = c(506, 533, 668, 677),
  g2treadss = c(590, 690, 789, 555),
  gktmathss = c(600, 655, 655, 665),
  g1tmathss = c(NA, 667, 556, 688),
  g2tmathss = c(NA, 700, 688, 789),
  gktrace = c(1, 2, 1, 1),
  g1trace = c(2, 1, 1, 2),
  g2trace = c(1, 1, 1, 1)
)

There are more years for each separate type of data and more types that I want to include.

This is what I want it to look like (obviously for more datapoints):

ID Gender treadss tmathss trace grade
1231 1 500 600 1 k
1231 1 506 NA 2 1
1231 1 590 NA 1 2
1232 2 533 655 2 k
1232 2 533 667 1 1
1232 2 690 700 1 2
1233 2 616 655 1 k
1233 2 668 556 1 1
1233 2 789 688 1 2
1234 1 599 665 1 k
1234 1 677 688 2 1
1234 1 555 789 1 2

A major issue is just how many variables there are. Some I want to use, some I don't want to, but I'm not sure how to make sure some of them don't get messed up.


Solution

  • You can pivot_longer your simple example dataframe d like this:

    df_long <- d %>%
      pivot_longer(cols = matches("g(k|[12])(.*)"),
                   names_to = c("grade", ".value"),
                   names_pattern = "g(k|[12])(.*)")  
    

    giving

    # A tibble: 12 × 6
          ID Gender grade treadss tmathss trace
       <dbl>  <dbl> <chr>   <dbl>   <dbl> <dbl>
     1  1231      1 k         500     600     1
     2  1231      1 1         506      NA     2
     3  1231      1 2         590      NA     1
     4  1232      2 k         533     655     2
     5  1232      2 1         533     667     1
     6  1232      2 2         690     700     1
     7  1233      2 k         616     655     1
     8  1233      2 1         668     556     1
     9  1233      2 2         789     688     1
    10  1234      1 k         599     665     1
    11  1234      1 1         677     688     2
    12  1234      1 2         555     789     1
    

    Similarly, you could pivot longer your wide data.frame df multiple times and left join it back with stdntid and grade.

    library(tidyr)
    library(dplyr)
    library(haven)
    
    
    reshape_educational_data <- function(df) {
      df <- df %>% 
        mutate(across(where(is.labelled), ~as.numeric(as_factor(.))))
      # FLAGSG type variables
      flags <- df %>%
        select(stdntid, matches("FLAGSG[k0-9]")) %>%
        pivot_longer(
          cols = matches("FLAGSG[k0-9]"),
          names_to = "grade",
          values_to = "flags",
          names_pattern = "FLAGSG?(.*)"
        ) %>%
        mutate(grade = ifelse(grade == "K", "0", grade))
      # FLAGG type variables
      flagg <- df %>% # flagg is a complicated one, it has values for 9 grades, the others don't
        select(stdntid, starts_with("FLAGG")) %>%
        pivot_longer(
          cols = starts_with("FLAGG"),
          names_to = "grade",
          values_to = "flagg",
          names_pattern = "flagg?(.*)"
        ) %>%
        mutate(grade = ifelse(grade == "k", "0", grade))
      
      # Class type variables
      class_type <- df %>%
        select(stdntid, matches("^g[k0-9]classtype$")) %>%
        pivot_longer(
          cols = matches("^g[k0-9]classtype$"),
          names_to = "grade",
          values_to = "class_type",
          names_pattern = "g(.*?)classtype"
        ) %>%
        mutate(grade = ifelse(grade == "k", "0", grade))
      
      # Test scores
      test_scores <- df %>%
        select(stdntid, matches("^g[k0-9]t(read|math)ss$")) %>%
        pivot_longer(
          cols = matches("^g[k0-9]t(read|math)ss$"),
          names_to = c("grade", "subject"),
          values_to = "score",
          names_pattern = "g(.*?)t(.*)ss"
        ) %>%
        mutate(
          grade = ifelse(grade == "k", "0", grade),
          subject = case_when(
            subject == "read" ~ "reading",
            subject == "math" ~ "math"
          )
        ) %>%
        pivot_wider(
          names_from = subject,
          values_from = score,
          names_glue = "{subject}_score"
        )
      
      # Attendance data
      attendance <- df %>%
        select(stdntid, matches("^g[k0-9](present|absent)$")) %>%
        pivot_longer(
          cols = matches("^g[k0-9](present|absent)$"),
          names_to = c("grade", "attendance_type"),
          values_to = "days",
          names_pattern = "g(.*?)(present|absent)"
        ) %>%
        mutate(
          grade = ifelse(grade == "k", "0", grade)
        ) %>%
        pivot_wider(
          names_from = attendance_type,
          values_from = days
        )
      
      # Teacher characteristics
      teacher_vars <- df %>%
        select(stdntid, matches("^g[k0-9]t(gen|race|highdegree|career|years)$")) %>%
        pivot_longer(
          cols = matches("^g[k0-9]t(gen|race|highdegree|career|years)$"),
          names_to = c("grade", "characteristic"),
          values_to = "value",
          names_pattern = "g(.*?)t(.*)$"
        ) %>%
        mutate(
          grade = ifelse(grade == "k", "0", grade)
        ) %>%
        pivot_wider(
          names_from = characteristic,
          values_from = value,
          names_prefix = "teacher_"
        )
      
      # School characteristics
      school_vars <- df %>%
        select(stdntid, matches("^g[k0-9](schid|surban)$")) %>%
        pivot_longer(
          cols = matches("^g[k0-9](schid|surban)$"),
          names_to = c("grade", "characteristic"),
          values_to = "value",
          names_pattern = "g(.*?)(schid|surban)"
        ) %>%
        mutate(
          grade = ifelse(grade == "k", "0", grade)
        ) %>%
        pivot_wider(
          names_from = characteristic,
          values_from = value,
          names_prefix = "school_"
        )
      
      # Combine all the reshaped data
      long_data <- df %>%
        select(all_of(c("stdntid", "gender"))) %>% # add more cols you want to keep
        cross_join(
          distinct(class_type, grade) %>% arrange(grade)
        ) %>%
        left_join(class_type, by = c("stdntid", "grade")) %>%
        left_join(test_scores, by = c("stdntid", "grade")) %>%
        left_join(attendance, by = c("stdntid", "grade")) %>%
        left_join(teacher_vars, by = c("stdntid", "grade")) %>%
        left_join(school_vars, by = c("stdntid", "grade")) %>%
        left_join(flags, by = c("stdntid", "grade")) %>%
        arrange(stdntid, grade)
      #res <- flagg %>% left_join(long_data, by = c("stdntid", "grade")) %>%
      return(long_data)
    }
    
    res <- reshape_educational_data(df)