将聚合输出转换为宽格式

时间:2017-06-07 08:40:00

标签: r reshape2

我使用函数聚合来制作长格式数据框架,但同事需要在Excel中使用它。我发现转换为宽格式很棘手。我需要制作列"变量"和"键入"分为几列,每列包含它们所包含的成员(前额,顶叶和枕叶)和(alpha,beta,gamma,delta和theta)。

dput(head(aggdata))
structure(list(Time = c(1, 2, 3, 4, 5, 6), Type = structure(c(1L, 
1L, 1L, 1L, 1L, 1L), .Label = c("alpha", "beta", "gamma", "delta", 
"theta"), class = c("ordered", "factor")), Group = structure(c(1L, 
1L, 1L, 1L, 1L, 1L), .Label = c("C", "N"), class = "factor"), 
    variable = structure(c(1L, 1L, 1L, 1L, 1L, 1L), .Label = c("Frontal", 
    "Parietal", "Occipital"), class = "factor"), Condition = c(1, 
    1, 1, 1, 1, 1), value = c(0.0947259533333333, 0.0489575420666667, 
    0.0686301660666667, 0.0754647909333333, 0.0708219834666667, 
    0.0644100006)), .Names = c("Time", "Type", "Group", "variable", 
"Condition", "value"), row.names = c(NA, 6L), class = "data.frame")

1 个答案:

答案 0 :(得分:1)

您可能需要查看reshape2包,以及dcast和melt功能。 你在这里有一个很好的熔融数据集,你想要投射。

让我先改变你的样本数据,因为它没有给几个变量传播。

agg_data <- rbind(agg_data,head(agg_data,1))
agg_data$variable[7] <- "Parietal"
agg_data$value[7] <- 0.0686301660666667
agg_data

# Time  Type Group variable Condition      value
# 1    1 alpha     C  Frontal         1 0.09472595
# 2    2 alpha     C  Frontal         1 0.04895754
# 3    3 alpha     C  Frontal         1 0.06863017
# 4    4 alpha     C  Frontal         1 0.07546479
# 5    5 alpha     C  Frontal         1 0.07082198
# 6    6 alpha     C  Frontal         1 0.06441000
# 7    1 alpha     C Parietal         1 0.06863017

这是我认为你想要的那条线:

dcast(agg_data, Time  + Type + Group + Condition ~  variable)

# Time  Type Group Condition    Frontal   Parietal
# 1    1 alpha     C         1 0.09472595 0.06863017
# 2    2 alpha     C         1 0.04895754         NA
# 3    3 alpha     C         1 0.06863017         NA
# 4    4 alpha     C         1 0.07546479         NA
# 5    5 alpha     C         1 0.07082198         NA
# 6    6 alpha     C         1 0.06441000         NA

在左侧放置要聚合的数据,在右侧放置要扩散的变量,可以在右侧放置一个变量并在几个变量上展开,例如:

dcast(agg_data, Time  + Group + Condition ~  variable + Type)

# Time Group Condition Frontal_alpha Parietal_alpha
# 1    1     C         1    0.09472595     0.06863017
# 2    2     C         1    0.04895754             NA
# 3    3     C         1    0.06863017             NA
# 4    4     C         1    0.07546479             NA
# 5    5     C         1    0.07082198             NA
# 6    6     C         1    0.06441000             NA