我正在尝试使用Reshape2库来融合R中的数据框,使用此函数:
mtable <- melt(df, id = "type")
print(mtable)
但我收到一条错误消息:Error in prettyNum(.Internal(format(x, trim, digits, nsmall, width, 3L, dims [product 3] do not match the length of object [24]
。数据框如下所示:
+---+--------+----------+----------+----------+----------+----------+----------+----------+----------+
| | type | x150 | x250 | x300 | x350 | x450 | x575 | x675 | x800 |
+---+--------+----------+----------+----------+----------+----------+----------+----------+----------+
| 1 | Long | 1.882222 | 1.129333 | 0.941111 | 0.806667 | 0.627407 | 0.491014 | 0.418272 | 0.352917 |
+---+--------+----------+----------+----------+----------+----------+----------+----------+----------+
| 2 | Middle | 1.44 | 0.864 | 0.72 | 0.617143 | 0.48 | 0.375652 | 0.32 | 0.27 |
+---+--------+----------+----------+----------+----------+----------+----------+----------+----------+
| 3 | Short | 1.0975 | 0.6585 | 0.54875 | 0.470357 | 0.365833 | 0.286304 | 0.243889 | 0.205781 |
+---+--------+----------+----------+----------+----------+----------+----------+----------+----------+
错误意味着什么,以及如何将数据框从宽格式转换为长格式?
dput(head(df))
的输出:
structure(list(type = structure(c(3L, 2L, 1L), .Label = c("bottom",
"middle", "top"), class = "factor"), x150 = structure(c(1.88222222222222,
1.44, 1.0975), .Dim = 3L), x250 = structure(c(1.12933333333333,
0.864, 0.6585), .Dim = 3L), x300 = structure(c(0.941111111111111,
0.72, 0.54875), .Dim = 3L), x350 = structure(c(0.806666666666667,
0.617142857142857, 0.470357142857143), .Dim = 3L), x450 = structure(c(0.627407407407407,
0.48, 0.365833333333333), .Dim = 3L), x575 = structure(c(0.491014492753623,
0.375652173913043, 0.286304347826087), .Dim = 3L), x675 = structure(c(0.418271604938272,
0.32, 0.243888888888889), .Dim = 3L), x800 = structure(c(0.352916666666667,
0.27, 0.20578125), .Dim = 3L)), .Names = c("type", "x150", "x250",
"x300", "x350", "x450", "x575", "x675", "x800"), row.names = c("0",
"1", "2"), class = "data.frame")
答案 0 :(得分:2)
不确定您的数据是如何获得的,但您有数组作为观察。我通过转换为矩阵来取消效果。并重新绑定到数据框。您可能想要研究为什么有这种奇怪的数据帧结构。
class(df[,2])
[1] "array"
melt(cbind(df[1], as.matrix(df[-1])), id = "type")
# type variable value
# 1 top x150 1.8822222
# 2 middle x150 1.4400000
# 3 bottom x150 1.0975000
# 4 top x250 1.1293333
# 5 middle x250 0.8640000
# 6 bottom x250 0.6585000
# 7 top x300 0.9411111
# 8 middle x300 0.7200000
# 9 bottom x300 0.5487500
# 10 top x350 0.8066667
# 11 middle x350 0.6171429
# 12 bottom x350 0.4703571
# 13 top x450 0.6274074
# 14 middle x450 0.4800000
# 15 bottom x450 0.3658333
# 16 top x575 0.4910145
# 17 middle x575 0.3756522
# 18 bottom x575 0.2863043
# 19 top x675 0.4182716
# 20 middle x675 0.3200000
# 21 bottom x675 0.2438889
# 22 top x800 0.3529167
# 23 middle x800 0.2700000
# 24 bottom x800 0.2057812