R shiny fileInput - backslashes leading to upload error - r

I am having difficulties in R Shiny with the fileInput. I am able to successfully upload multiple .txt or .csv files, however I want my application to be able to upload a filetype called ".fcs" files as well. In order to read such ".fcs" files, I have used the library flowCore under the bioConductor package. Within this flowcore package, there is a function called read.FCS that I often use to read in ".fcs" files into R.
The first argument of the read.FCS() function is a character string of the location of the file. This is where my issue lies: because the function needs the filepath to be in a charcater string, the backslashes in the datapath generated by fileInput() don't mesh with the character string expected by read.FCS (for example, when I print the datapath acquired from fileInput, Shiny returns something like: ...\AppData\Local\Temp\Rtm...PdV/99...42/0 - note the forward and backslashes).
My question is: is there any way to modify the datapath to not include backslashes, so that the read.FCS() function can work properly?
To illustrate this proble, I will attach a simplified version of my scripts below for debugging purposes, as well as a method to generate a .txt file and a .fcs file (you must first install the package flowCore). You will be able to read these both into R, but the .fcs file will be incapable of being read into the Shiny app. Upon launching shiny, when you select the “.txt” File Type option and upload the sample .txt file (generate below),Shiny heads this file. When you relaunch the app and select the “.fcs” file type option and upload the sample .fcs file (generated below), the file does not properly upload.
At first I thought this was Shiny corrupting the FCS file somehow upon upload. But this is not the case. As prrof, in the mainTab area you will see a printed file path. If you copy this filepath (when you have attempted to load the fcs file), put it in quotes and put it into the read.FCS(insert copied file path with quotes around it here), you will get an error. If, on the other hand, you replace all of the “\” with “/” in the read.FCS command and try it again, R will successfully read the file that was uploaded to Shiny. Thus, I am led to believe that if I could somehow replace the “\” with “/” in the filepath, I will be able to read my FCS files.
Thanks so much for the help – I really appreciate it: sample code attached below
install.packages(flowCore)
library(flowCore)
x = rnorm(n=20, mean=5, sd=10)
y = rnorm(n=20, mean=5, sd=10)
z = rnorm(n=20, mean=5, sd=10)
data<-data.frame(as.integer(x),as.integer(y),as.integer(z))
my_save_path<-"C:/Users/drew/Desktop/"
write(as.matrix(data), paste(my_save_path, "sample_textfile.txt", sep=""), ncolumns=3, sep="\t")
df.export<-new("flowFrame", as.matrix(data))
write.FCS(df.export, paste(my_save_path, "sample_fcsfile.fcs", sep=""))
#write.fcs is experimental, but the problem persists for raw .fcs files from other sources other than this export.
#####Verify that these files are real and can be looked at in r
txt.real<-read.delim(paste(my_save_path,"sample_textfile.txt", sep=""))
txt.real #yup, reading into R works
fcs.real<-read.FCS( paste(my_save_path, "sample_fcsfile.fcs", sep=""), transform=FALSE)
fcs.real<-exprs(fcs.real)
fcs.real #yup, this is real too
User Interface
shinyUI(navbarPage("App",
tabPanel("Overview",
sidebarLayout(
sidebarPanel("Load in Data",
selectInput("filetype", label = h3("File Type"),
choices=list(".fcs file", ".txt file"), selected=".txt file"),
fileInput("files", h3("File(s) Input"))),
mainPanel(
tableOutput("table1"),
textOutput("text")
)))
))
Server
library(flowCore)
shinyServer(function(input, output) {
fileName<-reactive({
inFile <- input$files
inFile$datapath
})
dataInput<-reactive({
if(input$filetype==".fcs file"){
library(flowCore)
FCS<-read.FCS(fileName(), transform=FALSE)
exprs(FCS)
}
if(input$filetype==".txt file") {
TXT<-read.delim(fileName())
TXT
}
})
####Heading the Table (debug)
output$table1<-renderTable({
if (is.null(input$files))
return(NULL)
head(dataInput())
})
#Seeing the file path
output$text<-renderText({
x<-fileName()
x
})
}
)

Related

List of file paths to iteratively pass through sourced python function in Shiny

I have come up with a python function that I have confirmed works just fine. I am trying to put this into a Shiny app using Shiny's reticulate. I am not super familiar with Shiny but need to use it anyhow.
To give a bit of background on what I am doing, I've written some python code that takes takes multiple files and matches strings based on one common list of strings. This code works fine when I run the python files on my machine.
I need to make this available to others using a shiny app, where they can upload their files, then have the app run the underlying python code.
So far, I have set up the shiny app so that it can take in multiple files. I am having a hard time thinking about how I can use reactive to make a list of the file path names to then send to my python code (which includes a step to open and read the file) so it can do its thing.
This is the code that I have for my app thus far:
library(shiny)
library(shinyFiles)
# define UI
ui <- fluidPage(
titlePanel('Counter of Gendered Language'),
fileInput("upload", "Choose a folder",
multiple = TRUE,
accept = c('text')),
tableOutput('text'),
downloadButton('output', 'Download Count File .csv'))
# define server behavior
server <- function(input, output){
# Setup
#* Load libraries
library(reticulate)
#* Use virtual environment for python dependencies
use_virtualenv('file/path/py_venv', required = TRUE)
#* Source code
source_python('code/counting_gendered_words.py')
#* Load list of words to match raw text against
dictionary <- read.csv('data/word_rating.csv')
text <- reactive(
list <- list.files(path = input$upload[['name']])
)
output$counted <- gendered_word_counter(dictionary, text())
output$downloadData <- downloadHandler(
filename = function(){
paste0(input$upload, ".csv")
},
content = function(file){
vroom::vroom_write(text$counted, file)
}
)
}
# Run the application
shinyApp(ui = ui, server = server)
What it tells me when I run this app is that:
Error : Operation not allowed without an active reactive context.
You tried to do something that can only be done from inside a reactive consumer.
So what I am wanting to do is basically just pass each file name that someone uploads to the app and pass that file's name into my gendered_word_counter() python function.
How would I go about this?
I'm super confident that I just am being a newbie and it is probably a super simple fix. Any help from those who are more comfortable with Shiny would be much appreciated!
Edit: I notice that my code is only calling the names of the files which is meaningless for me without the contents of the uploaded files! Would it be better if I read the files in the shiny app instead of in my .py file?
I can't reproduce the app without the python code, but i can see that this line:
output$counted <- gendered_word_counter(dictionary, text())
has a reactive object (text()) being called with no reactive context. It should be wrapped in observe or observeEvent.
observe({
output$counted <- gendered_word_counter(dictionary, text())
})
Also let's add the parenthesis here:
content = function(file){
vroom::vroom_write(text()$counted, file)
}

R Shiny select files from server-side directory

I have a folder called logs filled with different .csv files, formatted as telemetryLog-2017.21.08.54.11.csv (with varying dates and times at end).
For example, the above file could be stored like this: file <- read.csv("logs/telemetryLog-1969.2017.21.08.54.11.csv", header=TRUE)
The log files would be uploaded (in the logs folder, to shinyapps.io) along with the ui.R and server.R files. I would like to be able to obtain a list of the filenames in order to be able to select a file to display as data in a plot via selectInput (or any other way to list the files). The amount of files in the folder will not be an excessive amount; most likely it will be limited to around 50.
I have read the documentation for shinyFiles and to be completely honest I do not fully understand how the commands such as fileGetter or dirGetter work. Any help would be appreciated.
Instead of having people browse the file system of your server, you could also use list.files and specify the right directory there:
library(shiny)
ui <- fluidPage(
selectInput('selectfile','Select File',choice = list.files('log/')),
textOutput('fileselected')
)
server <- function(input,output)
{
output$fileselected <- renderText({
paste0('You have selected: ', input$selectfile)
})
}
shinyApp(ui,server)
Hope this helps!

Using Shiny fileInput to get path only

I have a very large fixed width file I need to read in using my Shiny application. The way my program is currently structured is the ui.R contains a fileInput allowing the user to locate the file using the browser.
On the server side, I only capture the path to the file such as the following:
path2file <- reactive({
infile <- input$path2file
if (is.null(infile)) return(NULL)
infile$datapath
})
A subsequent function takes that path as input and the proceeds to read in the file according to its layout specifications. This all works just fine; however when dealing with extremely large fwf files my program slows down tremendously and takes hours to get the path name of the file read in using fileInput
My suspicion is that fileInput is actually reading in the entire file and then my function only returns the datapath even though I am not explicitly reading in any file format type within the function.
My aim is to continue using the program as I have it structured now and obtain only the path to this file using my fileInput. I have found this topic on SO, and see it is a possible option.
Getting file path from Shiny UI (Not just directory) using browse button without uploading the file
However, I also aim to minimize the number of package dependencies I have; this has become a big issue and so if I MUST use an additional package I will, but I'd like to avoid that at all costs.
I experimented with this cheap trick:
path2file <- reactive({
infile <- input$path2file
if (is.null(infile)) return(NULL)
scan(infile$datapath, n = 1)
infile$datapath
})
Thinking that it would be a fast workaround, but it too is extremely slow so I suspect it too is not reading in only n = 1. So, my question is can anyone identify a way to use fileInput to allow a user to locate a file and have the server side function capture only the path and NOT read in the file or try and parse it in any way? More importantly, can this be done using functions in base R and Shiny alone without having to grab functions from other extended packages?
The above is the relevant portion of code in the server.R file and the relevant portion of code in the ui.R file is
fileInput('path2dor', 'Choose the DOR .txt file to format',
accept=c('text/csv',
'text/comma-separated-values,text/plain', '.csv')),
Thank you for you advice.
This functionality is not possible with fileInput. The reason is because 'fileInput' do not provide local path information to the server for security reasons.
With fileInput the user navigates through the browser on his local machine, the resulting file on the server side is the uploaded copy of the selected local once.
As an alternative you can use the shinyFiles package, which do navigate through the server side. This means, that you get all the paths on your local machine.
A second alternative could be a simple text input, which lets the user add a path by hand (make sure to check the path on the server side to not run into any troubles).
As pointed by others, due to security concerns shiny creates a tmp folder with all files loaded called with fileinput
Accordingly, you need to select all the files of interest in your folder and then call this tmp file with ...$datapath
Note however that each element of datapath will include both the directory information and the corresponding file name. Accordingly, you need to trim those paths to only account for the tmp directory. This can be achieved as follows...
Assume you will create an object called phu which will only contain the first file in the folder (using input$upload$datapath[1]) you called with fileInput("upload", NULL, buttonLabel = "Upload...", multiple = TRUE)
phu<-as.character(input$upload$datapath[1])
phu<-substr(phu,1,nchar(phu)-5)
The second line removes the last five characters in the string. These characters are 0.txt or whatever other extension you called in your input. The code provided only works with .txt files and requires the tm package. You can now use the object phu as the input directory of interest.
Finally, you need to call this output with an output object and print it in your ui this is shown with textOutput("Pdiretory") below.
The following example shows the entire process. Note that there are no security concerns because this temporary file and its content will be deleted at closing. Once more, the input files are .txt files.
library(shiny)
library(tm)
ui <- fluidPage(
fileInput("upload", NULL, buttonLabel = "Upload...", multiple = TRUE),
textOutput("Pdiretory")
)
server <- function(input, output, session) {
listdir <- eventReactive(input$upload, {
phu<-as.character(input$upload$datapath[1])
phu<-substr(phu,1,nchar(phu)-5)
txt<-Corpus(DirSource(phu),readerControl = list(language = "en"))
print(txt)
})
output$Pdiretory <- renderPrint ({
listdir()
})
}
shinyApp(ui = ui, server = server)

Uploading picture to the knitr document via Shiny

I am using combination of Shiny and knitr to create PDF documents.
Currently I want to add feature that will allow user to upload picture that will be placed within the created document. However, I am really stuck because I am unable to get the path of the input picture. Could anyone help me with that?
Simple example:
Application:
library(knitr)
library(shiny)
ui <- fluidPage(
sidebarLayout(
sidebarPanel(
fileInput("picture", label = 'Picture'),
downloadButton('report', label = 'Download PDF')
),
mainPanel()
)
)
server <- function(input,output){
picture <- reactive({
input$picture[,4]
})
output$report = downloadHandler(
filename = "test.pdf",
content = function(file){
picture = picture()
out = knit2pdf(input = 'test.Rnw', compiler = 'xelatex', clean = TRUE)
file.rename(out, file)
},
contentType = 'application/pdf'
)
}
shinyApp(ui = ui, server = server)
and the .Rnw document:
\documentclass{article}
\begin{document}
Put picture here:
<<echo = FALSE , message = F, results='asis'>>=
cat(paste('\\includegraphics[height=3in]{', picture,'}'))
#
\end{document}
Part '\includegraphics[height=3in]{', picture,'} is obviously causing the problem, because I do not know the picture path only temporary one.
You said you were working with Shiny Server, then you should be okay with the full path of the picture, even if it is in a temporary directory (because currently Shiny Server only works on Linux, and LaTeX should be okay with Linux file paths like /tmp/...../yourfile.png). The problem is perhaps the datapath (i.e. input$picture[, 4]) does not have the file extension, so LaTeX could not recognize it. You may try to retrieve the filename extension of the original file, and copy the uploaded picture to a temp file with the same extension, e.g.
picture <- reactive({
path1 <- input$picture$datapath
path2 <- tempfile(fileext = gsub('^(.*)([.].+)$', '\\2', input$picture$name))
file.copy(path1, path2, overwrite = TRUE)
path2
})
i see a solution in two ways:
1) copy the temporary file to a folder of your choice and use that image:
observe({
if (is.null(input$picture)) return()
picture<-"your/final/path/to/disk/uploadImage.jpg" # OR do a PASTE with the PATH and the upload file name
file.copy(input$picture$datapath, picture)
if(file.exists(picture)){
# PROCESS THE IMAGE IF NEEDED
}
picture<<-picture # sometimes needed to R to see the variable outside the observe scope
})
2) if you (in this case the R session) are not allowed to write to disk you can turn the image into a base64 variable and include that into your Knitr document (or save it to a database as a string). This takes the Knitr/HTML route if you are willing to take that detour. (R studio running from a server almost always has a lot of restrictions in reading/writing that you can only handle as an ADMIN. And the server runs the shiny session as RStudio and not you so Rstudio must have the read/write permissions needed if you run the Shiny app as an automatic Rstudio Shiny session and not run it directly form RStudio using RUN)
Make sure the base64 is readable by R ouside the 'observe' or 'if' scope again by using '<<-' together with '<-'. Scoping is quite something special with R so be sure to test it properly.
You should dive into this (base64) with sites like:
https://github.com/yihui/knitr/issues/944
https://github.com/yihui/knitr/blob/master/R/utils-base64.R

RShiny: How to pass variable from Server.R to an RMD script

I am playing around with RShiny recently, and I've built a working web interface that takes two parameters "date" and "location" and gives me back a series of graphs and tables from our database that fit the criteria.
What I would like to do with that, is to have users being able to download all the data and graphs in the form of a RMD report in HTML format.
so I have
1. UI.R with a download button
2. Server.R's downloadHandler starts my RMD script
3. ????
UI.R
downloadButton('downloadData','Download')
Server.R
output$downloadData<- downloadHandler(filename ="myData.html",
content= function(file= NULL){
knit(thread.RMD)
}
Here is the answer I got from the Shiny Google Group : https://groups.google.com/forum/?fromgroups=#!topic/shiny-discuss/XmW9V014EtI
The function that's given as the 'content' argument to downloadHandler takes one option, 'file'. When the download button is clicked, the download handler calls that function, and it uses the file argument to tell it where is should save the output file.
I don't see a way to set the output file name from knit2html(), but you can just rename it after it's created:
output$downloadData <- downloadHandler(
filename ="ShinyData.html",
content = function(file) {
knit2html("myreport.rmd")
file.rename("myreport.html", file)
}
)
(Also, you're missing a closing parenthesis in ui.r.)
-Winston

Resources