firmo23
firmo23

Reputation: 8404

Newly created function is not found in working directory

I replicate the code from here in order to create the HWplot() function with:

#HWplot.R

library(ggplot2)
library(reshape)


HWplot<-function(ts_object,  n.ahead=4,  CI=.95,  error.ribbon='green', line.size=1){

  hw_object<-HoltWinters(ts_object)

  forecast<-predict(hw_object,  n.ahead=n.ahead,  prediction.interval=T,  level=CI)


  for_values<-data.frame(time=round(time(forecast),  3),  value_forecast=as.data.frame(forecast)$fit,  dev=as.data.frame(forecast)$upr-as.data.frame(forecast)$fit)

  fitted_values<-data.frame(time=round(time(hw_object$fitted),  3),  value_fitted=as.data.frame(hw_object$fitted)$xhat)

  actual_values<-data.frame(time=round(time(hw_object$x),  3),  Actual=c(hw_object$x))


  graphset<-merge(actual_values,  fitted_values,  by='time',  all=TRUE)
  graphset<-merge(graphset,  for_values,  all=TRUE,  by='time')
  graphset[is.na(graphset$dev),  ]$dev<-0

  graphset$Fitted<-c(rep(NA,  NROW(graphset)-(NROW(for_values) + NROW(fitted_values))),  fitted_values$value_fitted,  for_values$value_forecast)


  graphset.melt<-melt(graphset[, c('time', 'Actual', 'Fitted')], id='time')

  p<-ggplot(graphset.melt,  aes(x=time,  y=value)) + geom_ribbon(data=graphset, aes(x=time, y=Fitted, ymin=Fitted-dev,  ymax=Fitted + dev),  alpha=.2,  fill=error.ribbon) + geom_line(aes(colour=variable), size=line.size) + geom_vline(x=max(actual_values$time),  lty=2) + xlab('Time') + ylab('Value') + opts(legend.position='bottom') + scale_colour_hue('')
  return(p)

}

The function seems to be created normally but when I try to load it using:

source("HWplot.R")

I get:

Error in file(filename, "r", encoding = encoding) : 
  cannot open the connection
In addition: Warning message:
In file(filename, "r", encoding = encoding) :
  cannot open file 'HWplot.R': No such file or directory

Upvotes: 0

Views: 31

Answers (1)

Matias Andina
Matias Andina

Reputation: 4220

If you run list.files(pattern='HWplot.R') what do you get?

character(0)

This means the file is not in the working directory, as evidenced by the error R was throwing:

cannot open file 'HWplot.R': No such file or directory

This could be due to 2 reasons.

1. File is actually not in working directory

You are calling source("HWplot.R"). This assumes that this file is in the working directory.

I would recommend doing getwd() and locating where you saved your HWplot.R file, they should be in the same directory if you want your source() command to work. As a general rule source(path/to/file).

You can also run list.files() to see what's actually in the directory.

2. Typo

Happened to me a million times. Check that the spelling of your R code and the file's name matches, otherwise it will never find it!

Upvotes: 1

Related Questions