Newly created function is not found in working directory - r

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

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!

Related

Error in setwd() : cannot change working directory Execution halted

i am trying to pass external arguments to R when calling a Rscript with a command line in that i am getting an Error in setwd(args[8]) : cannot change working directory
Execution halted
Not sure why this error is occurring Please suggest some ideas to sort out
Any idea would be appreciated
Rscript /home/mike/learn-analysis/SL_input.R chr21 10542449 10542649 + Y Y 1 /mnt/prep/learn/CA-21-10542394-10542448.2.D.txt D /home/mike/learn-analysis/SL_table.R
#SL_table.R file
args <- commandArgs(trailingOnly = TRUE)
setwd(args[8]) # directory to write file to
source(args[11]) # can be updated to reflect location of source code
results<-SL_mutate(args[1],args[2],args[3],args[4],args[5],args[6],args[7]) # chrom, start, stop, strand, gene, transcript, exon number
results$type<-args[10]
results$transcript<-NULL
results$exon_num<-NULL
write.table(results,args[9],quote = F, row.names = F, sep="\t") # write to filename given in argument (in working directory)

R: Cannot run certain function after cleaning temporary directory

I get the error:
Error in file(fn, "rb") : cannot open the connection
In addition: Warning message:
In file(fn, "rb") :
cannot open file 'C:\Users\***\AppData\Local\Temp\Rtmpwh6Zih\raster\r_tmp_2020-05-
13_170601_12152_33882.gri': No such file or directory
When I run the following code in RStudio (1.2.5042):
raster.binair <- vector(mode = "list", length = length(aggregated.rasters))
for (i in 1:NROW(aggregated.rasters)) {
+ clamped <- clamp(aggregated.rasters[[i]], upper=12, useValues=FALSE)
+ raster.binair[[i]] <- clamped
+ }
"aggregated.rasters" is a list of 96 rasters and when I separately run it, I get the correct list. I recently cleaned my temporary directory (accessed by tempdir()) and deleted the files in there. I suppose the part:
cannot open file 'C:\Users\***\AppData\Local\Temp\Rtmpwh6Zih\raster\r_tmp_2020-05-
13_170601_12152_33882.gri': No such file or directory
is referring to this. I don't know what I did wrong here. Can I get these files back or work around this error?
Files in the temp folder are deleted when an R session ends. So you should never count on them. You can run the code again, but if you want to permanently keep the results you need to write them elsewhere. Here are two options
Write many files
raster.binair <- vector(mode = "list", length = length(aggregated.rasters))
for (i in 1:NROW(aggregated.rasters)) {
f <- paste0("raster_", i)
clamped <- clamp(aggregated.rasters[[i]], upper=12, useValues=FALSE, filename=f)
raster.binair[[i]] <- clamped
}
Write a single file
raster.binair <- vector(mode = "list", length = length(aggregated.rasters))
for (i in 1:NROW(aggregated.rasters)) {
raster.binair[[i]] <- clamp(aggregated.rasters[[i]], upper=12, useValues=FALSE)
}
s <- stack(raster.binair)
s <- writeRaster(s, filename="mydata.tif")

Error when reading/writing in the temp directory (using arulesSequences in R-studio)

When I run the following code:
s1 <- cspade(x, parameter = list(support = 0.1, maxsize = 1, maxlen = 1),
control = list(verbose = TRUE))
I receive the following error:
Total elapsed time 0.00286102
1 partition(s), 0 MB [0.12s]
mining transactions ...MINSUPPORT 1 out of 4 sequences
reading sequences ...cannot open file
'C:\Users\ERKANE~1\AppData\Local\Temp\RtmpohPsWy\cspade3894f1b4b9f.out': No
such file or directoryError in file(con, "r") : cannot open the connection
When I check the directory, I do not see any .out file. I have attempted to change the TMPDIR to another location, but still received the same error. I run r-studio as admin, but still receive the same error. I am able to create a file in the same directory write.csv(mtcars,paste(tempdir(),"mtcars.csv",sep="\\")). Any ideas?
I am using R version 3.5.1 and RStudio-1.1.456.

gganimate package in R cannot link to ImageMagick

Running the awesome gganimate package, but can't get the base example to work.
library(gapminder)
library(ggplot2)
library(gganimate)
theme_set(theme_bw())
p <- ggplot(gapminder, aes(gdpPercap, lifeExp, size = pop, color = continent, frame = year)) + geom_point() + scale_x_log10()
gg_animate(p)
Returns:
sh: C:\Program Files\ImageMagick-6.9.0-Q16\convert.exe: command not found
Error in cmd.fun(sprintf("%s --version", shQuote(ani.options("convert"))), : error in running command
sh: convert: command not found
Error in cmd.fun(sprintf("%s --version", convert), intern = TRUE) :
error in running command
I cannot find ImageMagick with convert = 'convert'
Error in file(file, "rb") : cannot open the connection
In addition: Warning messages:
1: In im.convert(img.files, output = movie.name, convert = convert, :
Please install ImageMagick first or put its bin path into the system PATH > variable
2: In normalizePath(movie.name) :
path[1]="file4421bbcfb7d.gif": No such file or directory
3: In file(file, "rb") :
cannot open file > '/var/folders/4y/5nw21h2j1dz9p960gfvl16ywlrpqh8/T//RtmpRywpkt/gganimate/file4421bb> cfb7d.gif': No such file or directory
I'm almost sure ImageMagick is installed. What is the missing link?

Error trying to read a PDF using readPDF from the tm package

(Windows 7 / R version 3.0.1)
Below the commands and the resulting error:
> library(tm)
> pdf <- readPDF(PdftotextOptions = "-layout")
> dat <- pdf(elem = list(uri = "17214.pdf"), language="de", id="id1")
Error in file(con, "r") : cannot open the connection
In addition: Warning message:
In file(con, "r") :
cannot open file 'C:\Users\Raffael\AppData\Local\Temp
\RtmpS8Uql1\pdfinfo167c2bc159f8': No such file or directory
How do I solve this issue?
EDIT I
(As suggested by Ben and described here)
I downloaded Xpdf copied the 32bit version to
C:\Program Files (x86)\xpdf32
and the 64bit version to
C:\Program Files\xpdf64
The environment variables pdfinfo and pdftotext are referring to the respective executables either 32bit (tested with R 32bit) or to 64bit (tested with R 64bit)
EDIT II
One very confusing observation is that starting from a fresh session (tm not loaded) the last command alone will produce the error:
> dat <- pdf(elem = list(uri = "17214.pdf"), language="de", id="id1")
Error in file(con, "r") : cannot open the connection
In addition: Warning message:
In file(con, "r") :
cannot open file 'C:\Users\Raffael\AppData\Local\Temp\RtmpKi5GnL
\pdfinfode8283c422f': No such file or directory
I don't understand this at all because the function variable is not defined by tm.readPDF yet. Below you'll find the function pdf refers to "naturally" and to what is returned by tm.readPDF:
> pdf
function (elem, language, id)
{
meta <- tm:::pdfinfo(elem$uri)
content <- system2("pdftotext", c(PdftotextOptions, shQuote(elem$uri),
"-"), stdout = TRUE)
PlainTextDocument(content, meta$Author, meta$CreationDate,
meta$Subject, meta$Title, id, meta$Creator, language)
}
<environment: 0x0674bd8c>
> library(tm)
> pdf <- readPDF(PdftotextOptions = "-layout")
> pdf
function (elem, language, id)
{
meta <- tm:::pdfinfo(elem$uri)
content <- system2("pdftotext", c(PdftotextOptions, shQuote(elem$uri),
"-"), stdout = TRUE)
PlainTextDocument(content, meta$Author, meta$CreationDate,
meta$Subject, meta$Title, id, meta$Creator, language)
}
<environment: 0x0c3d7364>
Apparently there is no difference - then why use readPDF at all?
EDIT III
The pdf file is located here: C:\Users\Raffael\Documents
> getwd()
[1] "C:/Users/Raffael/Documents"
EDIT IV
First instruction in pdf() is a call to tm:::pdfinfo() - and there the error is caused within the first few lines:
> outfile <- tempfile("pdfinfo")
> on.exit(unlink(outfile))
> status <- system2("pdfinfo", shQuote(normalizePath("C:/Users/Raffael/Documents/17214.pdf")),
+ stdout = outfile)
> tags <- c("Title", "Subject", "Keywords", "Author", "Creator",
+ "Producer", "CreationDate", "ModDate", "Tagged", "Form",
+ "Pages", "Encrypted", "Page size", "File size", "Optimized",
+ "PDF version")
> re <- sprintf("^(%s)", paste(sprintf("%-16s", sprintf("%s:",
+ tags)), collapse = "|"))
> lines <- readLines(outfile, warn = FALSE)
Error in file(con, "r") : cannot open the connection
In addition: Warning message:
In file(con, "r") :
cannot open file 'C:\Users\Raffael\AppData\Local\Temp\RtmpquRYX6\pdfinfo8d419174450': No such file or direc
Apparently tempfile() simply doesn't create a file.
> outfile <- tempfile("pdfinfo")
> outfile
[1] "C:\\Users\\Raffael\\AppData\\Local\\Temp\\RtmpquRYX6\\pdfinfo8d437bd65d9"
The folder C:\Users\Raffael\AppData\Local\Temp\RtmpquRYX6 exists and holds some files but none is named pdfinfo8d437bd65d9.
Intersting, on my machine after a fresh start pdf is a function to convert an image to a PDF:
getAnywhere(pdf)
A single object matching ‘pdf’ was found
It was found in the following places
package:grDevices
namespace:grDevices [etc.]
But back to the problem of reading in PDF files as text, fiddling with the PATH is a bit hit-and-miss (and annoying if you work across several different computers), so I think the simplest and safest method is to call pdf2text using system as Tony Breyal describes here.
In your case it would be (note the two sets of quotes):
system(paste('"C:/Program Files/xpdf64/pdftotext.exe"',
'"C:/Users/Raffael/Documents/17214.pdf"'), wait=FALSE)
This could easily be extended with an *apply function or loop if you have many PDF files.

Resources