0
我有這樣的(df1
)如何更有效地將我的數據框重塑爲新的形式(R)?
ID 2 4 6 8 10 12 14 16 18 20 22 24 Day
1 0 0 0 0 2 0 0 0 1 0 1 0 Sunday
1 0 0 0 0 0 4 0 0 0 0 0 0 Monday
1 0 0 0 0 0 0 0 0 2 0 0 0 Tuesday
1 0 0 0 0 0 0 2 0 0 0 0 0 Wednesday
1 0 0 0 0 0 0 0 2 0 0 0 0 Thursday
1 0 0 0 0 0 0 0 0 2 0 0 0 Friday
1 0 0 0 0 0 0 0 0 0 2 0 0 Saturday
2 0 0 0 0 0 0 0 0 0 0 0 0 Sunday
2 0 0 0 0 0 1 0 0 0 0 0 0 Monday
2 0 0 0 0 0 0 1 0 0 0 1 0 Tuesday
2 0 0 0 0 0 0 0 1 0 0 0 0 Wednesday
2 0 0 0 0 0 0 0 0 1 0 0 0 Thursday
2 0 0 0 0 0 2 0 0 0 1 0 0 Friday
2 0 0 0 0 0 0 0 0 0 0 0 0 Saturday
3 0 0 0 0 0 0 0 0 0 0 0 0 Sunday
3 0 0 0 0 0 0 2 0 0 0 0 0 Monday
3 0 0 0 0 0 1 0 0 2 0 0 0 Tuesday
3 0 0 0 0 0 0 0 0 0 0 0 0 Wednesday
3 0 0 0 0 0 0 0 2 0 0 0 0 Thursday
3 0 0 0 0 0 0 0 0 0 0 0 0 Friday
3 0 0 0 0 0 0 2 0 0 0 0 0 Saturday
3 0 0 0 0 0 0 0 2 0 0 0 0 Sunday
的數據集,我有一個ID
清單如下:
ID
1
2
3
我想了df1
轉換成這種類型的輸出:
ID Var1 Var2 Var3 Var4 Var5 ...... Var82 Var83 Var84
1 0 0 0 0 2 2 0 0
2
3
其中Var1
代表'星期天2'(在第一個數據幀中),var84代表'Saturday24'。我想將我的結果導出爲.csv
文件。
我這樣做是通過使用for循環(如下所示),因爲有太多的ID。但是,問題是這些代碼運行速度很慢。有沒有更快的方法來獲得相同的結果?
library(dplyr)
library(reshape2)
for (i in ID_checklist$ID) {
x= filter(df1$ID %in% i)
x$Day = NULL
df.melted = melt(t(x[,-1]), id.vars = NULL)
myNewDF = data.frame(i, t(df.melted[,3]))
write.table(myNewDF,file="my12x7.csv", append=TRUE,sep=",",col.names=FALSE,row.names=FALSE)
}