r - 将 R 数据帧从长格式转换为宽格式,但组大小不相等,用于 qcc

标签 r reshape qcc

我想将数据帧从长格式转换为宽格式,但组大小不相等。

最终使用将在“qcc”中,这需要一个数据框或矩阵,每行由一组组成,在样本较少的组中使用 NA。

以下代码将创建一个示例数据集,并显示手动转换为所需格式。

# This is an example of the initial data that I have
# * 10 sample measurements, over 3 groups with 3, 2, and 5 elements respectively
x <- rnorm(10)
x_df <- data.frame( time = c( rep('2001 Q1',3), rep('2001 Q2',2), rep('2001 Q3',5) ), measure = x )
x_df

# This is a manual conversion into the desired format
x_pad <- c( x[1:3], NA, NA, x[4:5], NA, NA, NA, x[6:10] )
x_matrix <- matrix( x_pad, nrow = 3, ncol = 5, byrow = TRUE, dimnames = list(c('2001 Q1','2001 Q2','2001 Q3')) )
x_matrix # desired format

# An example of how it will be used
library(qcc)
plot(qcc(x_matrix, type = 'xbar', plot = FALSE))

所以,我想转换这个:
      time     measure
1  2001 Q1  0.14680685
2  2001 Q1  0.53593193
3  2001 Q1  0.56097974
4  2001 Q2 -1.48102689
5  2001 Q2  0.18150972
6  2001 Q3  1.72018147
7  2001 Q3 -0.08480855
8  2001 Q3 -2.23208877
9  2001 Q3 -1.15269107
10 2001 Q3  0.57975023

……到这……
              [,1]        [,2]       [,3]      [,4]      [,5]
2001 Q1  0.1468068  0.53593193  0.5609797        NA        NA
2001 Q2 -1.4810269  0.18150972         NA        NA        NA
2001 Q3  1.7201815 -0.08480855 -2.2320888 -1.152691 0.5797502

可能有一种简单的方法(也许我不熟悉 reshape 或 reshape2 cast 的一些用法?),但到目前为止,一堆搜索对我没有帮助。

谢谢你的帮助!

==========

从以下解决方案之一,以下将生成最终的 qcc xbar 图,包括组标签:
library(splitstackshape)
out_df <- dcast( getanID( x_df, 'time' ), time~.id, value.var='measure' )
qcc( out_df[,-1], type = 'xbar', labels = out_df[,1] )

最佳答案

您可以使用 getanID 创建序列列 ('.id')来自 splitstackshape并使用 dcast来自 data.table将长格式转换为宽格式。 splitstackshape 的输出是一个数据表。当我们加载 splitstackshape , data.table 也将被加载。因此,如果您已经拥有 data.table 的开发版本,那么 dcast来自 data.table也可以使用。

library(splitstackshape)
dcast(getanID(df1, 'time'), time~.id, value.var='measure')
#     time          1           2          3         4         5
#1: 2001 Q1  0.1468068  0.53593193  0.5609797        NA        NA
#2: 2001 Q2 -1.4810269  0.18150972         NA        NA        NA
#3: 2001 Q3  1.7201815 -0.08480855 -2.2320888 -1.152691 0.5797502

更新

正如评论中提到的@snoram,函数rowid来自 data.table只需 data.table 就更容易使用独自的
library(data.table)
dcast(setDT(df1), time ~ rowid(time), value.var = "measure")

关于r - 将 R 数据帧从长格式转换为宽格式,但组大小不相等,用于 qcc,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31700020/

相关文章:

r - ROC曲线反向绘制的特异性

r - Lime:glmnet(x[, c(features, j) 中的错误,x 应该是具有 2 列或更多列的矩阵

r - 如何在 QCC Xbar 图表中显示日期

c++ - 与 if 进行比较时与与存储值进行比较时的 std::vector删除结果不同

r - 如何使用 ggplot2 从 qcc 包重现 pareto.chart 图?

GNU R 的 Python 替代品

r - 如何记录 r 包的数据集?

python - Pandas 将具有相同名称但不同后缀的列转换为索引并将索引转换为列

python - 如何 reshape 元组数组

r - strsplit 融化的数据集