【问题标题】:reshaping rows of data to two columns将数据行重塑为两列
【发布时间】:2021-03-02 19:48:14
【问题描述】:

我们有学区的数据,其中列是当地特定信息(例如,免费和减价午餐百分比)和相应的全州值。

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

我们想要重塑它,让它看起来像这样。

  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

这似乎是 pivot_longer 应该能够处理的事情,但到目前为止我还没有取得太大的成功。有什么建议吗?

【问题讨论】:

标签: r tidyverse


【解决方案1】:

我们可以使用pivot_longer

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

-输出

# 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

【讨论】:

  • 完美。谢谢!
【解决方案2】:

使用reshape 的基本 R 选项

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

给予

# 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

【讨论】:

  • 很高兴知道。谢谢!
猜你喜欢
  • 2022-09-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-02-14
  • 2016-12-05
  • 2012-07-28
  • 2020-10-16
  • 1970-01-01
相关资源
最近更新 更多