我想知道如何将行转换为以下数据集的列。
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
我使用了分离功能,但是徒劳无功。
提前致谢
答案 0 :(得分:1)
我们可以使用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
或使用spread
tidyr
library(tidyr)
spread(df1, Sub, Subavg)