add local image file in R presentation - r

I'm trying to include one imaging file (.png) using R markdown for R presentation.
I followed the suggestion from: How to import local image using knitr for markdown
but by using ![title](my.png), I get this error:
Error: unexpected '[' in "!["
The my.png file is in current path. I also tried using absolute path but got the same error message.
Putting above inside the r chuck failed too.
I also tried
```{r,fig.width=350, fig.height=250,echo=FALSE}
library(png)
library(grid)
appimg <- readPNG('my.png')
grid.raster(appimg)
```
but failed too!
I am working on windows 7 R studio 0.98.1102 and R 3.2.1 .

After a huge mount of Google search. I finanlly figure out what is the problem.
The key is that HTML cannot refer local file for security reason. Except that it is a local HTML file, then it can refer local file in the same file directory.
And R presentation is actually a HTML file like a webpage.
So, just put your image file the same directory with the HTML file, things will work. At least it worked for me.
Just use
![some caption](img_file_name.png)

Removing the quotes actually worked for me and note that one better doesn't keep any spaces while naming the image as in use,
![title](my_image.png)
Using quotes or having spaces(when renamed) hasn't worked for me in this case.

The 'imager' package makes this pretty easy:
library(imager)
myimg <- load.image("<pathto>/file.png")
plot(myimg)

If your output format is : slidy_presentation
You can use html code:
<img src="/Users/name/folder/xyz.png";>
Further, if you wish to align and adjust the image to a specific side (say right of your final output and specify a size) you can use something like -
<img src="/Users/name/folder/xyz.png"; style="max-width:280px;float:right;">

Related

"The system cannot find the file specified whenever I knit"

Whenever I knit to a PDF in RStudio, the error "The system cannot find the file specified."
Here is the code that I'm using:
##importing data
library(readr)
Quiz1data_2 <- read_csv("C:/Users/erinp/Downloads/Quiz1data-2.csv")
I have restarted RStudio multiple times and I have copied and pasted the exact link that my file is saved to and it's still not working.
What am I not seeing or what am I not thinking?
Some suggestions/questions:
Without knitting, when you run the line reading in the csv, does it work?
Also, are you sure that the error is referring to the data csv? Could it be referring to the (I'm assuming) markdown file you are writing your code in? Have you moved that file since you started working in it?
Are you able to knit other documents to pdf? You need MiKTeX on a windows machine. Does knitting to html work?
I've found R to be a little tricky reading in files. I usually use the base function like this:go to the environment tab>import dataset>from text(base)> (select the file you want, hit open)>(select settings so that the dataframe preview looks right>import. Code that does this will run in the console, and I copy it into my markdown file so that every time it knits, it replicates that successful process.
I figured it out. It's because I forgot to assign a value to an object so it wouldn't knit into a PDF. I made a comment earlier, but it's small so I thought I would add this to the answer section.

Read a file in R without changing the working directory

How can others who run my R program read a file(eg: csv) used in my R code without having to change the working directory in setwd()?
I will suggest you use the here() function in the here package in your code like this:
library(here)
Data1 <- read_csv(here("test_data.csv"))
read.csv has a file argument and if I were to quote from the inbuilt R help about file:
If it does not contain an absolute path, the file name is relative to
the current working directory, getwd().
So, providing the absolute path of the file inside the file argument solves this problem.
In Windows
Suppose your file name is test.csv and it's located in D:\files\test_folder (you can get the location of any file from its properties in Windows)
For reading this file you run:
df<-read.csv('D:\\files\\test_folder\\test.csv')
or
df<-read.csv('D:/files/test_folder/test.csv')
Suggested reading: Why \\ instead of \ and Paths in programming languages
Haven't used R in Linux but maybe Getting a file path in Linux might help
Read from web
Just type in the web address of the dataset in the file attribute. Try:
df<-read.csv('https://raw.githubusercontent.com/AdiPersonalWorks/Random/master/student_scores%20-%20student_scores.csv')
Note: This link contains a list of 25 students with their study hours and marks. I myself used this dataset for one of my earlier tasks and its perfectly safe

What is the right way to show up images at R Markdown?

I am doing an html document from R Markdown (RStudio) and I think I am following the right instructions to show it up. I read the R's Bookdown (https://bookdown.org/yihui/rmarkdown) and there says this is the way, or at least this is what I get from it. I am using this only script line to make the image calling:
![Hadley Wickham](Macintosh HD/Usuarios/ivanmendivelso/Dropbox/Escuela/IntroR Vids/HW.jpeg).
When knitting I get this error message: "File Macintosh HD/Usuarios/ivanmendivelso/Dropbox/Escuela/IntroR Vids/HW.jpeg not found in resource path
Error: pandoc document conversion failed with error 99
Execution halted".
Does anybody know what am I doing wrong? Why I can not see images in my documents?
Thanks in advance.
It looks like your path is not correct.
If the image can be moved, put it in the same directory as your .Rmd file. If you can't move it to the file directory and if you don't speak UNIX, you can get the path by:
Finding the file with the finder
Right click on it
hold the option key on your keyboard and you will see the menu change from Copy "HW.jpg" to say Copy "HW.jpeg" as pathname
Paste that path into your code.
When you have file spaces in your file path you need to put single quotes around to make them strings
![Hadley Wickham](‘Macintosh HD’/Usuarios/ivanmendivelso/Dropbox/Escuela/‘IntroR Vids’/HW.jpeg)
What about this below
![Hadley Wickham](/Macintosh HD/Usuarios/ivanmendivelso/Dropbox/Escuela/IntroR Vids/HW.jpeg).
notice the / at the begining of the file path. on Mac the very first / is meaning from the root of your hard drive

How do I assign the working directory for rmarkdown/knitr interactive doc on shinyApps.io?

I have a fully functional interactive shiny doc using knitr/r markdwon.
However, when I try to publish (deploy) it to shinyApps.io, I get an error saying the .PNG file I try to incorporate into the doc (using readPNG from the png package) is unable to open.
I know the problem is related to working directories.
In my original code I assigned a working directory to my folder (i.e., "C:/Users/NAME/documents/...." that contains both my .rmd file and my .png file. However, obviously my folder doesn't exist on the shinyapps.io.
So how exactly do I set my working directory to open the .png file via my doc on shinyapps.io?
I can't find anywhere that explicitly walks through this process. Please help explain this simply/basically for me.
Example:
Assume I have a folder in "C:/Users/NAME/documents/Shiny" that contains 2 files: "shiny.rmd" and "pic.png". I want "pic.png" to be rendered in my shiny.rmd doc.
Currently I have:
---
title: "TroubleShoot"
output: html_document
runtime: shiny
---
```{r ,echo=FALSE,eval=TRUE}
library(png)
library(grid)
direct <- "C:/Users/NAME/documents/Shiny/"
img <- readPNG(paste0(direct,"pic.PNG"))
grid.raster(img)
```
How do I rewrite my code so it works on shinyApps.io?
Do I need to create and name folders in specific ways to place my 2 files into before deploying?
When you paste the c drive to direct, and read the direct into img, you are sending the app/markdown to your local drive. You need to use a relative path to the project. I would suggest something like:
direct <- "./"
Which uses the relative path, not the absolute path.
That said you might be able to skip that step entirely if the .png is in the same folder as the shiny object. just call the file name and format and leave it as that.
Also, check you use of ". Your syntax highlighting indicates your code won't run properly as it thinks some of your functions and variables are character strings because you've misplaced your quotes around read.png(). That's probably just a copy and paste typo though.
In summary, call the image via grid.raster("./pic.PNG"), and brush up on how working directories and relative paths work.
In the absence of knowing exactly how you're 'setting' your working directory:
In rStudio to correct and easiest approach is to make a 'New Project' for every New Project. You can do this as the first step in your project, or you can add a project file to an existing directory.
When you do this it automatically sets your working directory correctly. The way you seem to be doing it is not correct, you are merely supplying a 'path'. If you were to not want to use a project for some reason (I can't think of a case where that would be right), then you can always use setwd(), however, I believe this needs to be used in every session. A true project doesn't have that requirement.
This will then allow you to deploy your app properly as it will update the working directory to the one on the host machine at shinyapps.io when it is initialised there.
Finally, using the correct relative syntax "./path/to/my.file" to reference all your assets, images, data etc, should correct your issue as stated in the question.

Calling Skim from inside R

I'm making a simple line in r to automatically open my generated plots.
I output the plots to a file called "plots.pdf" in the same directory as my r file, and at the end i use this two lines to try to open it:
dir <- paste("/Applications/Skim.app/Contents/MacOS/Skim ",getwd(),"/plots.pdf",sep="")
system(dir)
Basically, dir concatenates the full path of the skim app and the full path of the generated plot.
If i run the string stored at dir in a shell it works perfect, it opens the pdf file in Skim, but when i run it with system() from inside R it doesn't work (Skim says 'The document “plots.pdf” could not be opened.').
I believe this is a very little mistake somewhere in the syntax regarding the absolute/relative paths, but haven't managed to find it... Any advice is welcome! (Or a better way to achieve the same)
I found a way to bypass that problem, i just changed the path to Skim for the 'open' command and i let the system to assign the default app for pdf viewing. So:
dir <- paste("open ",getwd(),"/plots.pdf",sep="")
And it works.

Resources