Clickable link to local folder in Rmarkdown - r

I was wondering if it is possible to add a link of a local directory or file to rmarkdown. My goal is to have a png in each page, and a clickable link on some of the pages that take me to the file that plots are generated from (special file, so no csv, or tables).I don't want to open the file, but just open the folder that has that file, so user can easily find it and open it with appropriate software.
Something like this:
{r, results='asis'}
#Generate some plots
for (i1 in 1:10)
{
png(paste0("~/Downloads/tmp-png/",i1,".png"), width=800, height=800)
par(mfrow=c(3,3))
for (j1 in 1:9)
plot(1:40)
dev.off()
}
some.list <- c("2.png","5.png","7.png")
files <- list.files(path = "~/Downloads/tmp-png", pattern = "png",
full.names = TRUE)
for (f in files) {
cat(paste0("![image_label](", f, ")\n"))
if ( f %in% some.list)
#Add a local hyperlink to the folder
#
}

You didn't say what the link should be, but you should be able to generate one using something like your image inclusion. E.g. if the link you want for file f is to folder temp/foo.wjx, then just include
folder <- "temp/foo.wjx"
cat(paste0("[folder_label](", folder, ")\n"))
after the if.
This needs to be a folder on the web server with a path relative to the path to the PDF file making the link. Whether the PDF viewer follows the link probably depends on which viewer you are using.
The folder_label could be an image link instead of a text label.

Related

How to See Hidden Files in a File Dialog Using R?

Using RStudio on our Linux server, I am attempting to display a file dialog in R that allows the user to see hidden files (files that begin with a period {.*} that are visible with ls -a). I have tried the following file.choose() and rstudioapi::selectFile() with different options, but the hidden files remain hidden in the file dialog in each case:
myHiddenFile1a <- file.choose()
myHiddenFile1b <- file.choose(new = TRUE)
myHiddenFile2a <- rstudioapi::selectFile()
myHiddenFile2b <- rstudioapi::selectFile(existing = FALSE)
myHiddenFile2c <- rstudioapi::selectFile(filter = ".*")

Saving Multiple Html Sources in R

I have created the following code
library('XML')
library('rvest')
links <- c('https://www.google.com/',
'https://www.youtube.com/?gl=US',
'https://news.google.com/news/u/0/headlines?hl=en&ned=us')
for (i in 1:3){
html_object <- read_html(links[i])
write_xml(html_object, file="test.html")
}
I want to save all of these files as html files, but my current code is only saving one. I am guessing that it keeps rewriting the same file 3 times for this example. How would I make it so that it does not rewrite the same file? Ideally, I would like the file name for these html files to be their url link, but I am unable to figure out how to do that with multiple links. For example, my end result should be three HTML files titled 'https://google.com/', 'https://www.youtube.com/?gl=US', and 'https://news.google.come/news/u/0/headlines?h1-en&ned=us'.
What about using paste0() to create your filename in the for-loop?
for(i in 1:length(links)){
html_object <- read_html(links[i])
somefilename <- paste0("filename_", i, ".html")
write_xml(html_object, file = somefilename)
}

Save base64 JPG to disk in R - Shiny

I have the following data frame which can be downloaded from here. The column image_path has jpg files in base64 format. I want to extract the image and store it in a local folder. I tried using the code given here and here.
While the second one perfectly opens the image in the browser, I couldn't figure out how to save the file locally. I tried the following code:
library(shiny)
for (i in 1:length(df)){
file <- paste(df$id[i])
png(paste0(~images/file, '.png'))
tags$img(src = df$image_path[i])
dev.off()
}
The following just runs but doesn't create any image files and no errors are shown. When I tried running tags$img(src = df$image_path[1]) to see if it generates the image, it doesn't. I understand tags$img is a function within shiny and works when I pass it inside ui (as suggested by #daatali), but not sure how do I save the files locally.
What I want is to run a for loop from inside a server environment of shiny and save the images locally as jpg using id numbers as filename, which can be rendered with various other details captured in the survey.
I have never worked with images and please bear with me if this is completely novice.
This creates your images from the base64 strings and saves the files to your current working directory, subfolder "/images/". This article describes pretty well how to save files locally in Shiny.
library(shiny)
library(base64enc)
filepath <- "images/"
dir.create(file.path(filepath), showWarnings = FALSE)
df <- read.csv("imagefiletest.csv", header=T, stringsAsFactors = F)
for (i in 1:nrow(df)){
if(df[i,"image_path"] == "NULL"){
next
}
testObj <- strsplit(df[i,"image_path"],",")[[1]][2]
inconn <- testObj
outconn <- file(paste0(filepath,"image_id",df[i,"id"],".png"),"wb")
base64decode(what=inconn, output=outconn)
close(outconn)
}

When using servr::jekyll() on R, where should I save my Rmd files?

With the Rmd files on root (eg. on my /knitr-jekyll/) they are turning into md files, but not on html files. Thus, they appear as simple markdown text.
I tried to put them on /_source and on /_posts but it get's worse, in this case I also don't get the md files.
I found creating a separate folder all together solves the problem.
/kintr-jekyll/_rmd/test.Rmd
But do remember that when you knit your Rmd to md that you knit to the _post folder if you using the standard bootstrap template. Also make sure that you specified your figure output. Easiest is to write some function which does this for you:
KnitPost <- function(input, base.url = "/") {
require(knitr)
opts_knit$set(base.url = base.url)
fig.path <- paste0("figures/", sub(".Rmd$", "", basename(input)), "/")
opts_chunk$set(fig.path = fig.path)
opts_chunk$set(fig.cap = "center")
render_jekyll()
knit(input, envir = parent.frame())
Lastly, go make sure in your .md file in knitr-jekyll/_post that the figures are clearly referenced. This should be within your test.md:
<img align="middle" src="/figures/test/test_image.jpg">
This link might help: R-Bloggers post about jekyll

How can one copy-paste local png files to a word document using R?

I have ~10,000 png images saved neatly in different files on my PC. I want to write a function that does something like go to a particular folder and iteratively copy-pastes all the png files in that folder to a word document. Is this possible in R?
I've looked at package R2wd but it sadly only has a function that takes RData and outputs its plot to a word document (function wdPlot).
I also have the RData saved for each and every plot, so reason would dictate that I should be able to simply load the RData associated with a particular plot and then use wdPlot . The problem is that when I generated my png's the plots were grobs and I did something as follows:
png("rp.png",width=w,height=h)
plot(rp)
#Increase size of title
grid.edit(gridTitle_Ref, gp=gpar(fontsize=20))
#Other grid.edit alterations
dev.off()
save(rp)
Now, when I try to get that rp onto a word document by first loading it into R I naively do the following and it does not output a plot to MS Word with the title enlarged or any of the other grid.editalterations.
load("rp.Rdata")
png("rp.png",width=w,height=h)
wdPlot(rp)
#Increase size of title
grid.edit(gridTitle_Ref, gp=gpar(fontsize=20))
#Other grid.edit alterations
dev.off()
So, to reiterate: I have all these png files. At various times I have to copy-paste a subset of them into a word document. I'm too lazy to do that manually each time and want a program to do it for me.
EDIT 1
So, as per suggestions below, I've read up on Markdown. Following this post How to set size for local image using knitr for markdown?
I wrote something along the lines of:
```{r,echo=FALSE,fig.width=100, fig.height=100}
# Generate word documents of reports
# Clear all
rm(list=ls())
library(png)
library(grid)
library(knitr)
dir<-"location\of\file"
setwd(dir)
# Output only directories:
folders<-dir()[file.info(dir())$isdir]
for(folder in folders){
currentDir<-paste(dir,folder,"\\",sep="")
setwd(currentDir)
#All files in current folder
files<-list.files()
imgs<-[A list of all the png images in this particular file that I want in the word document - the png names]
for(img in imgs){
imgRaster<-readPNG(img)
grid.raster(imgRaster)
}
}
```
The following is a screenshot of what's in the resulting word document. How might I fix this? I want the images to appear one after the other in the document as the for loop above runs.
Do note that this is the first time I've ever used Markdown so any relevant tutorials linked in the comments could also be of great help.
EDIT 2
I followed the second answer's example below. Here is the output that I obtained
As you can see there are no images, only the html tags. How do I fix this?
If you have the png's saved you can just use a little html and a for loop to save them to a .doc file.
edit 2 for windows
# Start empty word doc
cat("<body>", file="exOut.doc", sep="\n")
# select all png files in working directory
for(i in list.files(pattern="*.png"))
{
temp <- paste('<img src=', i, '>')
cat(temp, file="exOut.doc", sep="\n", append=TRUE)
}
cat("</body>", file="exOut.doc", sep="\n", append=TRUE)
# Some example plots
for(i in 1:5)
{
png(paste0("ex", i, ".png"))
plot(1:5)
title(paste("plot", i))
dev.off()
}
# Start empty word doc
cat(file="exOut.doc")
# select all png files in working directory
for(i in list.files(pattern="*.png"))
{
temp <- paste('<img src=', i, '>')
cat(temp, file="exOut.doc", sep="\n", append=TRUE)
}
You will then need to embed the figures, either using the drop down menus or by writing a small macro that you can call with system
EDIT : small update to show explicit paths to output and figures
cat("<body>", file="/home/daff/Desktop/exOut.doc", sep="\n")
for(i in list.files(pattern="*.png"))
{
temp <- paste0('<img src=/home/daff/', i, '>')
cat(temp, file="/home/daff/Desktop/exOut.doc", sep="\n", append=TRUE)
}
Note that i used paste0 to remove the space between the path /home/daff/ and ex*.png.
Have you tried Rstudio and Markdown? You could put your code into chunks that load the files and save as word document. http://rmarkdown.rstudio.com/word_document_format.html

Resources