我有一个包含对象名称的数据框和该对象的统计矩列表,如下所示:
Object Mean IQR Skew
x 1 1 1
y 2 2 2
z 3 3 3
我想要的是为每一行创建具有统计时刻和对象名称前缀的列。像这样:
xMean xIQR xSkew yMean yIQR ySkew zMean zIQR zSkew
1 1 1 2 2 2 3 3 3
本质上我需要的是将数据框折叠成单行,以便在一行上列出所有统计矩,因为我会有许多行,如最后一行但是有限的一组列。 / p>
答案 0 :(得分:2)
你可以这样做:
df1$id <- 1
reshape(df1, idvar="id", timevar="Object", direction="wide")[-1]
# Mean.x IQR.x Skew.x Mean.y IQR.y Skew.y Mean.z IQR.z Skew.z
#1 1 1 1 2 2 2 3 3 3
或使用dcast
melt
,reshape2
library(reshape2)
dcast(melt(df1, id.var=c('id', 'Object')), id~..., value.var='value')[-1]
# x_Mean x_IQR x_Skew y_Mean y_IQR y_Skew z_Mean z_IQR z_Skew
#1 1 1 1 2 2 2 3 3 3
或使用dplyr
和tidyr
library(dplyr)
library(tidyr)
df1 %>%
gather(Var, Val, Mean:Skew) %>%
unite(VarNew,Object, Var, sep="") %>%
spread(VarNew, Val) %>%
select(-id)
# xIQR xMean xSkew yIQR yMean ySkew zIQR zMean zSkew
#1 1 1 1 2 2 2 3 3 3
df1 <- structure(list(Object = c("x", "y", "z"), Mean = 1:3, IQR = 1:3,
Skew = 1:3), .Names = c("Object", "Mean", "IQR", "Skew"), class = "data.frame", row.names = c(NA,
-3L))
答案 1 :(得分:1)
或者类似
setNames(unlist(data.frame(t(df[-1]))), paste0(rep(df[, 1], each = nrow(df)), names(df[, -1])))
# xMean xIQR xSkew yMean yIQR ySkew zMean zIQR zSkew
# 1 1 1 2 2 2 3 3 3