gganimate package in R cannot link to ImageMagick - r

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?

Related

Error in file(file, "rt") : invalid 'description' argument when running R script

I am trying to reproduce this protocol for DNA sequencing data analysis. It requires running this bash script that links to an R script. However, I am getting this error (see bottom) that I cant seem to solve.
#!/bin/bash
Project_dir=~/base
cd /${Project_dir}
SCRTP=~/scRepliseq-Pipeline
OUTNAME="bam/G1_F121_A1.adapter_filtered2"
genome_name="mm10"
bamfile=${OUTNAME}.${genome_name}.clean_srt_markdup.bam
rscript=${SCRTP}/util/Step3_R-Aneu-Fragment-bins.R
out_dir="Aneu_analysis"
Name=‘$bamfile’
Name=${name%.adapter_filtered2.${genome_name}.clean_srt_markdup.bam}
blacklist=~/blacklist/mm10-blacklist-v1_id.bed
genome_file=~/reference/UCSC_hg19_female.fa.fai
mkdir -p ${out_dir}
Rscript --vanilla $rscript ${bamfile} ${out_dir} ${name} ${blacklist} ${genome_file}
it links to this R script
args = commandArgs(TRUE)
bamfile=args[1]
out_dir=args[2]
name=args[3]
blacklist=args[4]
genome_file=args[5]
options(scipen=100)
##Extension of file name##
ext="_mapq10_blacklist_fragment.Rdata"
ext2="_mapq10_blacklist_bin.Rdata"
library(AneuFinder)
##loading black list and genome Info##
genome_tmp <- read.table(genome_file,sep="\t") #UCSC_mm9.woYwR.fa.fai
genome=data.frame(UCSC_seqlevel=genome_tmp$V1,UCSC_seqlength=genome_tmp$V2)
chromosomes=as.character(genome$UCSC_seqlevel)
##setup output directories##
out_dir_f=paste0(out_dir,"/fragment")
out_dir_b=paste0(out_dir,"/bins")
dir.create(out_dir,showWarnings = FALSE)
dir.create(out_dir_f,showWarnings = FALSE)
dir.create(out_dir_b,showWarnings = FALSE)
##save the fragment file (>10 MAPQ), filtering out the blacklist regions##
raw_reads=bam2GRanges(bamfile,remove.duplicate.reads = TRUE,min.mapq = 10,blacklist = blacklist)
save(raw_reads,file = paste0(out_dir_f,"/",name,ext))
##save the bin data file ##
bins_reads=binReads(raw_reads,
assembly=genome,
chromosomes=chromosomes,
binsizes=c(40000,80000,100000,200000,500000))
rpm=1000000/length(raw_reads)
bins_reads[["rpm"]]=rpm
save(bins_reads,file=paste(out_dir_b,"/",name,ext2,sep=""))
It shows this error:
Error in file(file, "rt") : invalid 'description' argument
Calls: read.table -> file
Execution halted

problem with installing package transformr and animating plot in r

I have a data frame named df and want to create an animated chart line.
here is my data frame and code for animating the plot.
co1<- tibble(age= c(10:14 ), pop=c(10,12,14,16,18), cn= c(10.1,12.1,14.25,16.09,18.3), country ="USA")
co2<- tibble(age= c(10:14 ), pop=c(10.5,12.6,14.5,16.5,18.5), cn= c(10.6,12.5,14.3,16.7,18.6), country ="brazil")
co3<- tibble(age= c(10:14 ), pop=c(10.9,12.9,14.9,16.9,18.9), cn= c(11.9,13.9,15.9,17.9,19.9), country ="niger")
df<- rbind(co1,co2,co3)
df <- pivot_longer(df, cols = c("pop", "cn"))
#plot
ggplot(df, aes(x = age, y = value, group = country, col = name)) + geom_line() +
labs(x = "age", y = "population") + transition_states(country, transition_length = 3, state_length = 0) +
ggtitle("country: {closest_state}") +
theme_bw()
but when I try to run the example provided, I get this error:
Error in transform_path(all_frames, states[[i]], ease, nframes[i], !!id, : transformr is required to tween paths and lines
following some questions I have tried to install package transformr and devtools::install_github("thomasp85/transformr") but both did not work and I got this error :
Warning in install.packages :
downloaded length 2292878 != reported length 3644763
Warning in install.packages :
URL 'https://cran.rstudio.com/src/contrib/sf_1.0-1.tar.gz': Timeout of 60 seconds was reached
Error in download.file(url, destfile, method, mode = "wb", ...) :
download from 'https://cran.rstudio.com/src/contrib/sf_1.0-1.tar.gz' failed
Warning in install.packages :
download of package ‘sf’ failed
The error messages indicate that there is an issue with installing the sf package. It looks like the CRAN mirror (https://cran.rstudio.com/) you are using is not responding. This might be a temporary issue.
You can try to select another mirror with chooseCRANmirror() or specify another mirror just to install the sf package:
install.packages('sf', repos='http://cran.us.r-project.org')
If that works try again to run devtools::install_github("thomasp85/transformr").

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
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!

r XBRL package "404 Not Found" error with Ubuntu

The following R code works fine from my Windows 8 laptop:
> inst<- "https://www.sec.gov/Archives/edgar/data/51143/000104746916010329/ibm-20151231.xml"
> options(stringsAsFactors = FALSE)
> xbrl.vars <- xbrlDoAll(inst, cache.dir = "XBRLcache", prefix.out = NULL, verbose=TRUE)
However, when I attempt to run it from my Ubuntu 16.04 machine, I receive the following output:
Error in fileFromCache(file) :
Error in download.file(file, cached.file, method = "auto", quiet = !verbose) :
cannot download all files
In addition: Warning message:
In download.file(file, cached.file, method = "auto", quiet = !verbose) :
URL 'https://www.sec.gov/Archives/edgar/data/51143/000104746916010329/ibm-20151231.xsd': status was '404 Not Found'
It's finding the initial xml file but then cannot find the referenced schemas. Any help would be appreciated. Thanks in advance.

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