【问题标题】:How to pivot/gather multiple groups/pairs of columns through genertating keys from the column names in R? [duplicate]如何通过从 R 中的列名生成键来旋转/收集多个组/列对? [复制]
【发布时间】:2020-10-05 09:37:31
【问题描述】:

我有以下数据集

grade9_math_zscore <- rnorm(10, 0,1)
grade9_science_zscore <- rnorm(10, 0,1)
grade10_math_zscore <- rnorm(10, 0,1)
grade10_science_zscore <- rnorm(10, 0,1)
grade9_math_passed_lab<- sample(0:1,10,replace=TRUE)
grade10_math_passed_lab<- sample(0:1,10,replace=TRUE)
grade9_science_passed_lab<- sample(0:1,10,replace=TRUE)
grade10_science_passed_lab<- sample(0:1,10,replace=TRUE)
grade9_math_used_comp  <- sample(0:1,10,replace=TRUE)
grade10_math_used_comp  <- sample(0:1,10,replace=TRUE)
grade9_science_used_comp  <- sample(0:1,10,replace=TRUE)
grade10_science_used_comp  <- sample(0:1,10,replace=TRUE)
students<-as.data.frame(cbind(grade9_math_zscore, grade9_science_zscore, grade10_math_zscore , grade10_science_zscore , grade9_math_passed_lab, grade10_math_passed_lab, grade9_science_passed_lab,  grade10_science_passed_lab, grade9_math_used_comp,  grade10_math_used_comp, grade9_science_used_comp, grade10_science_used_comp ))

我需要得到的输出(前 4 行)如下所示

  grade  course               z_score passed_lab used_comp
1     9    math    -0.287118228740724          0         0
2     9 science     0.421672812450803          0         0
3    10    math      1.66175637068003          1         1
4    10 science -0.000352193924396851          0         1

我一直在尝试使用 R 上的 dplyr 中的 pivot_longer 来解决这个问题。我主要需要帮助来找出 names_pattern 选项。另外,我似乎无法在一个命令中 gather(以 dplyr 术语)所有三列 z_score , passed_lab , used_comp

感谢任何编码解决方案或仅仅是建议。任何不使用 dplyr 的解决方案也值得赞赏。

【问题讨论】:

  • 在与rnormsample等函数共享示例时,请使用set.seed,以确保可重复性

标签: r dplyr pivot tidyverse reshape


【解决方案1】:

使用pivot_longer,您可以:

tidyr::pivot_longer(students, 
                    cols = everything(), 
                    names_to = c('grade', 'course', '.value'), 
                    names_pattern = 'grade(\\d+)_(.*?)_(.*)')

# A tibble: 40 x 5
#   grade course  zscore passed_lab used_comp
#   <chr> <chr>    <dbl>      <int>     <int>
# 1 9     math    -1.04           0         1
# 2 9     science  0.608          0         0
# 3 10    math     1.27           0         1
# 4 10    science  1.38           1         1
# 5 9     math    -1.30           1         1
# 6 9     science  0.582          1         1
# 7 10    math    -0.196          1         1
# 8 10    science -0.198          0         1
# 9 9     math    -1.28           1         1
#10 9     science  2.05           0         0
# … with 30 more rows

数据

不要cbind再添加as.data.frame,直接用data.frame构造dataframe。

students<-data.frame(grade9_math_zscore, grade9_science_zscore....)

【讨论】:

    猜你喜欢
    • 2018-04-26
    • 1970-01-01
    • 2018-07-26
    • 2019-04-08
    • 2016-11-23
    • 2019-06-12
    • 2019-04-14
    • 2019-04-27
    • 1970-01-01
    相关资源
    最近更新 更多