如何通过从R中的列名生成键来透视/收集多组/多对列?
我有以下数据集如何通过从R中的列名生成键来透视/收集多组/多对列?,r,dplyr,pivot,tidyverse,reshape,R,Dplyr,Pivot,Tidyverse,Reshape,我有以下数据集 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_passe
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 ))
我一直在尝试从R上的dplyr
中使用pivot\u longer
获取此信息。我需要的帮助主要是找出names\u模式
选项。另外,我似乎无法收集(用dplyr术语)所有三列z_分数,通过实验室,在一个命令中使用comp
欢迎提供任何编码解决方案或建议。不使用dplyr的任何解决方案也将受到欢迎。使用pivot\u更长的时间
您可以:
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
与rnorm
或sample
等函数共享示例时,请使用set.seed
,以确保再现性
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
students<-data.frame(grade9_math_zscore, grade9_science_zscore....)