如何将行转换为R中的列
how to transform rows to columns in R
我想知道如何将以下数据集的行转换为列。
School class Avg Subavg Sub
ABC 2 25.3 17.2 Geo
ABC 2 25.3 18.2 Mat
ABC 2 25.3 20.2 Fre
ABC 3 21.2 17.2 Geo
ABC 3 21.2 18.2 Mat
ABC 3 21.2 20.2 Ger
ABC 4 16.8 17.2 Ger
ABC 4 16.8 18.2 Mat
ABC 5 20.2 20.2 Fre
预期输出为
School Std stdavg Geo mat Ger Fer
ABC 2 25.3 17.2 18.2 NA 20.2
ABC 3 21.2 17.2 18.2 20.2 NA
ABC 4 25.3 NA 18.2 17.2 NA
ABC 5 25.3 NA NA NA 20.2
我用了拆分功能,但是没用。
提前致谢
我们可以使用dcast
library(data.table)
dcast(setDT(df1), School+class+Avg~Sub, value.var="Subavg")
# School class Avg Fre Geo Ger Mat
#1: ABC 2 25.3 20.2 17.2 NA 18.2
#2: ABC 3 21.2 NA 17.2 20.2 18.2
#3: ABC 4 24.8 NA NA 17.2 18.2
#4: ABC 5 24.8 20.2 NA NA NA
或使用 tidyr
中的 spread
library(tidyr)
spread(df1, Sub, Subavg)
我想知道如何将以下数据集的行转换为列。
School class Avg Subavg Sub
ABC 2 25.3 17.2 Geo
ABC 2 25.3 18.2 Mat
ABC 2 25.3 20.2 Fre
ABC 3 21.2 17.2 Geo
ABC 3 21.2 18.2 Mat
ABC 3 21.2 20.2 Ger
ABC 4 16.8 17.2 Ger
ABC 4 16.8 18.2 Mat
ABC 5 20.2 20.2 Fre
预期输出为
School Std stdavg Geo mat Ger Fer
ABC 2 25.3 17.2 18.2 NA 20.2
ABC 3 21.2 17.2 18.2 20.2 NA
ABC 4 25.3 NA 18.2 17.2 NA
ABC 5 25.3 NA NA NA 20.2
我用了拆分功能,但是没用。
提前致谢
我们可以使用dcast
library(data.table)
dcast(setDT(df1), School+class+Avg~Sub, value.var="Subavg")
# School class Avg Fre Geo Ger Mat
#1: ABC 2 25.3 20.2 17.2 NA 18.2
#2: ABC 3 21.2 NA 17.2 20.2 18.2
#3: ABC 4 24.8 NA NA 17.2 18.2
#4: ABC 5 24.8 20.2 NA NA NA
或使用 tidyr
spread
library(tidyr)
spread(df1, Sub, Subavg)