2016-09-25 58 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)