rnorouzian
rnorouzian

Reputation: 7517

long form dataset to long(er) form dataset using pivot_longer

I'm trying my input dataset to look like the output: I have tried: pivot_longer(input, hyp, math) from library(tidyverse) without success.

Is there a way to achieve my desired output?

input <- read.csv("https://quantdev.ssri.psu.edu/sites/qdev/files/nlsy_math_hyp_long.csv")

#==== A few rows of desired output:

       id var grade d_math d_hyp  grp
1     201  38     3      1     0 math
2     201  55     5      1     0 math
3     303  26     2      1     0 math
4     303  33     5      1     0 math
5    2702  56     2      1     0 math

Upvotes: 1

Views: 42

Answers (1)

akrun
akrun

Reputation: 887501

We select the columns of interest and do the pivoting

library(dplyr)
library(tidyr)
input %>%
    select(id, grade, math, hyp) %>%
    pivot_longer(cols = math:hyp, names_to = 'grp', values_to = 'var') %>% 
    mutate(d_math = +(grp == 'math'), 
           d_hyp = +(!d_math))%>% 
    arrange(desc(grp), id)

Upvotes: 1

Related Questions