Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Open pdf file from R

Tags:

r

pdf

I'm trying to open a pdf file from R. For this I'm using the openPDF() function from the Biobase package. It works well if the path to file does not contain spaces between words (e.g. "/Users/Admin/Desktop/test.pdf") but it does not work if the path contains spaces (e.g. /Users/Admin/Desktop/**My Project**/test.pdf). How can I make it accept any path or how should I automatically transform a given path such that is recognised by openPDF()? I would also like it to work on both mac and windows. Here is the code:

library(Biobase)
pdf("test.pdf")
plot(1:10)
dev.off()
openPDF(paste(getwd(), "/test.pdf", sep=""))
like image 926
aymer Avatar asked Dec 15 '22 06:12

aymer


2 Answers

No need for external packages. This will work with the base R function system()

For a Mac / Unix:

path = '/path/to/file.pdf'
system(paste0('open "', path, '"'))

For a PC:

path = '\path\to\file.pdf'
system(paste0('start "', path, '"'))

Or if you want the path fixed, you can just incorporate it right into the paste0 string and do it in one line:

system('open "/path/to/file.pdf"')
like image 93
CephBirk Avatar answered Dec 17 '22 20:12

CephBirk


It's a bug in openPDF. You can work around it by calling normalizePath.

openPDF(normalizePath("test.pdf"))

For the record, openPDF is just a wrapper to shell.exec under Windows so you can just call that instead.

like image 23
Richie Cotton Avatar answered Dec 17 '22 19:12

Richie Cotton