Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

reshaping rows of data to two columns

Tags:

r

tidyverse

We have data on school districts where the columns are the local-specific information (e.g., free and reduced price lunch %) and the corresponding statewide values.

dat <- tribble(
  ~state.poverty,  ~state.EL,  ~state.disability,  ~state.frpl, ~local.poverty, ~local.frpl, ~local.disability, ~local.EL,
  12.50592, 0.08342419, 0.12321831, 0.4495395, 25.23731, 0.6415712, 0.140739, 0.1469898)

dat
# A tibble: 1 x 8
  state.poverty state.EL state.disability state.frpl local.poverty local.frpl local.disability local.EL
          <dbl>    <dbl>            <dbl>      <dbl>         <dbl>      <dbl>            <dbl>    <dbl>
1          12.5   0.0834            0.123      0.450          25.2      0.642            0.141    0.147

We want to reshape that so that it looks like this.

  demog        state  local
  <chr>        <dbl>  <dbl>
1 poverty    12.5    25.2  
2 EL          0.0834  0.147
3 disability  0.123   0.141
4 frpl        0.450   0.642

It seems like something that pivot_longer should be able to handle, but I haven't had much success so far. Any suggestions?

like image 311
cwod Avatar asked Dec 31 '22 16:12

cwod


1 Answers

We can use pivot_longer

library(dplyr)
library(tidyr)
dat %>% 
  pivot_longer(cols = everything(), 
      names_to = c(".value", "demog"), names_sep = "\\.")

-output

# A tibble: 4 x 3
#  demog        state  local
#  <chr>        <dbl>  <dbl>
#1 poverty    12.5    25.2  
#2 EL          0.0834  0.147
#3 disability  0.123   0.141
#4 frpl        0.450   0.642
like image 52
akrun Avatar answered Jan 14 '23 04:01

akrun