2016-09-25 82 views
-1

i相SQL獲得RDBMS數據和要預測使用R.創建中的R日期列

這裏每日購買的是數據的第12行。 first 12 data

我想要做的就是像下面的圖像一樣存儲數據框,最後我會嘗試使用指數平滑法編寫函數來預測它在行中的每個項目標題。 Purpose of dataframe

到目前爲止,我已經成功完成了標題欄。但是我不能像上面的第二張圖一樣製作多個日期欄。這是迄今爲止代碼:

df1 <- data.frame() 
dailydate <- as.Date(as.POSIXct(data$date_placed)) 
newdate <- unique(dailydate) 
itemtitle <- as.character(data$title) 
newitemtitle <- unique(itemtitle) 
df1 <- data.frame(newitemtitle,t(dailydate)) 
Error in data.frame(newitemtitle, t(dailydate)) 

我不能添加新列到df1,也沒有找到匹配基於標題的每日數量的方式。我願意接受任何建議,這個問題

+1

嘗試使用'dput'而不是圖片向我們提供您的數據的樣本。 – user2100721

+0

@ user2100721是的,我最近讀過它並更新結果,是一個正確的? – user3292755

+0

如果您有任何疑問,請將其作爲一個整體發佈。保持原始問題上的編輯堆積,因此既無效答案,並保持答案作爲你的人質不是宿主SO作品 –

回答

2

這是使用reshape2包的好地方。

df1 <- structure(list(title = structure(c(5L, 3L, 6L, 1L, 7L, 2L, 1L, 
4L, 8L, 3L), .Label = c("d", "k", "m", "n", "q", "t", "u", "v" 
), class = "factor"), quantity = c(4L, 3L, 5L, 10L, 6L, 13L, 
4L, 6L, 12L, 1L), date_placed = structure(c(1L, 1L, 1L, 2L, 2L, 
3L, 3L, 4L, 5L, 5L), .Label = c("8/24/2013", "8/25/2013", "8/26/2013", 
"8/27/2013", "8/28/2013"), class = "factor")), .Names = c("title", 
"quantity", "date_placed"), row.names = c(NA, -10L), class = "data.frame") 

#install.packages("reshape2") 
reshape2:::dcast(df1, title ~ date_placed, value.var = "quantity", fill = 0) 

結果:

# title 8/24/2013 8/25/2013 8/26/2013 8/27/2013 8/28/2013 
#1  d   0  10   4   0   0 
#2  k   0   0  13   0   0 
#3  m   3   0   0   0   1 
#4  n   0   0   0   6   0 
#5  q   4   0   0   0   0 
#6  t   5   0   0   0   0 
#7  u   0   6   0   0   0 
#8  v   0   0   0   0  12 

這比其他答案的好處是,輸出是如你所願,現在可以操縱的data.frame,而不是表。

+0

感謝圖書館@Chrisss,我已經使用了''dcast''和''melt''函數的''reshape2''軟件包。但是,還有一個障礙。現在我有3列(''title'','''',''date_placed''),其中標題是重複的,但具有不同的''date_placed''和''quantity''。我怎麼可以用重複的''title'行做預測? – user3292755

+0

如果您想要更詳細的解決方案,您應該真的在數據上使用'dput()'來幫助我們重現您的問題。截至目前,我不明白這個問題。 'dcast'製作一個寬的data.frame,其中'title'的唯一值作爲行,'date_placed'的唯一值作爲列和單元格由'quantity'填充。 'title''不應該在最終數據中的任何地方複製。框架 – Chrisss

+0

是的,我最近使用'dput()'作爲R,並且在預測'unique'標題值時遇到麻煩 – user3292755

1

使用此轉換數據

xtabs(data = df1,quantity~title+date_placed) 

數據

df1 <- structure(list(title = structure(c(5L, 3L, 6L, 1L, 7L, 2L, 1L, 
4L, 8L, 3L), .Label = c("d", "k", "m", "n", "q", "t", "u", "v" 
), class = "factor"), quantity = c(4L, 3L, 5L, 10L, 6L, 13L, 
4L, 6L, 12L, 1L), date_placed = structure(c(1L, 1L, 1L, 2L, 2L, 
3L, 3L, 4L, 5L, 5L), .Label = c("8/24/2013", "8/25/2013", "8/26/2013", 
"8/27/2013", "8/28/2013"), class = "factor")), .Names = c("title", 
"quantity", "date_placed"), row.names = c(NA, -10L), class = "data.frame") 
2

另一種選擇是從spreadtidyr

library(tidyr) 
spread(df1, date_placed, quantity, fill = 0)