将数据框折叠为单行并根据R行创建新列 [英] Collapse data frame into single row and creating new columns based on row R
问题描述
我有一个带有对象名称的数据框,以及该对象的统计时刻列表,如下所示:
I have a data frame with object names and a list of statistical moments for that object, like this:
Object Mean IQR Skew
x 1 1 1
y 2 2 2
z 3 3 3
我要为每一行创建带有统计时刻和对象名称前缀的列.像这样:
What i want is to for each row create columns with the statistical moments and the object name prefixed. Like so:
xMean xIQR xSkew yMean yIQR ySkew zMean zIQR zSkew
1 1 1 2 2 2 3 3 3
xMean xIQR xSkew yMean yIQR ySkew zMean zIQR zSkew
1 1 1 2 2 2 3 3 3
从本质上讲,我需要将数据框折叠到一行,这样它就可以在一行上列出所有统计矩,因为我将有很多行,如最后一行,但列的数量有限.
In essence what I need is to collapse a data frame to a single row such that it list all statistical moments on a single line as i'll have many rows like the final one but a finite set of columns.
推荐答案
您可以这样做:
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
,reshape2
中的melt
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))
这篇关于将数据框折叠为单行并根据R行创建新列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!