无法重新创建函数R

时间:2019-11-01 03:41:23

标签: r plyr

我有找到here(这是底部附近的热图)的代码,我正在尝试重现它。
这是原始代码:

# http://margintale.blogspot.in/2012/04/ggplot2-time-series-heatmaps.html
library(ggplot2)
library(plyr)
library(scales)
library(zoo)

df <- read.csv("https://raw.githubusercontent.com/selva86/datasets/master/yahoo.csv")
df$date <- as.Date(df$date)  # format date
df <- df[df$year >= 2012, ]  # filter reqd years

# Create Month Week
df$yearmonth <- as.yearmon(df$date)
df$yearmonthf <- factor(df$yearmonth)
df <- ddply(df,.(yearmonthf), transform, monthweek=1+week-min(week))  # compute week number of month
df <- df[, c("year", "yearmonthf", "monthf", "week", "monthweek", "weekdayf", "VIX.Close")]
head(df)
#>   year yearmonthf monthf week monthweek weekdayf VIX.Close
#> 1 2012   Jan 2012    Jan    1         1      Tue     22.97
#> 2 2012   Jan 2012    Jan    1         1      Wed     22.22
#> 3 2012   Jan 2012    Jan    1         1      Thu     21.48
#> 4 2012   Jan 2012    Jan    1         1      Fri     20.63
#> 5 2012   Jan 2012    Jan    2         2      Mon     21.07
#> 6 2012   Jan 2012    Jan    2         2      Tue     20.69


# Plot
ggplot(df, aes(monthweek, weekdayf, fill = VIX.Close)) + 
  geom_tile(colour = "white") + 
  facet_grid(year~monthf) + 
  scale_fill_gradient(low="red", high="green") +
  labs(x="Week of Month",
       y="",
       title = "Time-Series Calendar Heatmap", 
       subtitle="Yahoo Closing Price", 
       fill="Close")

这就是我试图重现它的方式:

asset <- 'Macys'
ticker <- 'M'

start.date <- as.Date('2009-10-30')
end.date <- as.Date(Sys.Date())

getSymbols(ticker, src='yahoo', from=start.date,to = end.date)

Close <- get(ticker)

heat.data <- data.frame(date = time(Close),
                        Close,
                        year = format(time(Close),'%Y'),
                        month = format(time(Close),'%m'),
                        monthf = factor(format(time(Close),'%b')))

heat.data <- data.frame(heat.data,
                        weekday = wday(heat.data$date),
                        weekdayf = factor(format(heat.data$date,'%a')),
                        week = format(heat.data$date,format = "%W"))

heat.data$date <- as.Date(heat.data$date)

heat.data$yearmonth <- as.yearmon(heat.data$date)
heat.data$yearmonthf <- factor(heat.data$yearmonth)
heat.data <- ddply(heat.data,.(yearmonthf),transform,monthweek=1+week-min(week))

现在,当我跑步时,我在ddply收到此错误:

Error in Summary.factor(44L, na.rm = FALSE) : 
  ‘min’ not meaningful for factors
In addition: Warning message:
In Ops.factor(1, week) : ‘+’ not meaningful for factors

现在我的问题是我在做什么不同?它与heat.date$week是变量的类型有关吗?

对于df使用的CSV格式,很难回答这个问题,我们深表歉意。但是,感谢您的宝贵时间,我们很乐意提供其他信息。

谢谢您的时间。

0 个答案:

没有答案