简体   繁体   中英

reshaping rows of data to two columns

We have data on school districts where the columns are the local-specific information (eg, 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?

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

A base R option using reshape

reshape(
  dat,
  direction = "long",
  varying = 1:ncol(dat)
)

gives

# A tibble: 4 x 4
  time         state  local    id
  <chr>        <dbl>  <dbl> <int>
1 poverty    12.5    25.2       1
2 EL          0.0834  0.642     1
3 disability  0.123   0.141     1
4 frpl        0.450   0.147     1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM