2015-10-19 95 views
1

我試圖使用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

你可以發佈'dput(head(df))'的輸出嗎?變量的結構可能存在問題 –

+0

將其添加到問題中。 – OleVik

回答

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 
+0

那太快了,謝謝! – OleVik