R shiny downloadHandler- write.xlsx: invalid 'path' argument - r

I've been trying to write my first small shiny app that takes two .xlsx files and do inner_join (like SQL would do) and then let's you download the result .xlsx. But when I try to download the file, I get error message that says:
Error in path.expand(file) : invalid 'path' argument
Warning: Error in path.expand: invalid 'path' argument
Here is my ui.R:
shinyUI(pageWithSidebar(
headerPanel('A linker'),
sidebarPanel(
fileInput("data","Choose file"),
textInput('d_sheet','Write the name of the sheet to be modified',
value = "", placeholder = "e.g. List 1"),
textInput('d_col','Write the ID-number of column that contains the ID'),
fileInput("libr","Choose library"),
textInput("l_sheet","Write the name of sheet that contains the data",
value="",placeholder="e.g. List 1"),
textInput("l_col","write the ID-number of column that contains the ID"),
textInput("l_join","Write the ID-number of columns to be linked to the
file")
),
mainPanel(
p('This application allows you to link data from the LIBRARY to
the data of the FILE. FILE is the table to be enhanced by the new data,
LIBRARY is the source of the data.'),
downloadButton("dwnld_data",label ="Download"))))
and server.R:
shinyServer( function(input, output){
options(shiny.maxRequestSize = 9*1024^2)
res_file<-reactive({
input_File <- input$data#
file_sheet<-input$d_sheet#
file_col<-as.vector(input$d_col)#
lib_File<-input$libr#
lib_sheet<-input$l_sheet#
lib_col<-as.vector(input$l_col)#
lib_data<-as.vector(input$l_join)#
a_file<-read.xlsx(input_File,sheetName = file_sheet)
colnames(a_file)[1:file_col]<-"a"
colnames(a_file)[file_col:ncol(a_file)]<-"b"
colnames(a_file)[file_col]<-"ID"
l_file<-read.xlsx(lib_File,sheetName=lib_sheet)
tab_l<-l_file[,c(lib_col,lib_data)]
colnames(l_file)<-"ID"
r_file<-inner_join(a_file,l_file,by="ID")
r_file})
output$dwnld_data <- downloadHandler(
filename = function() {paste("result.xlsx")},
content = function(file) {
write.xlsx(res_file(),file, sheetName="List 1")
})})
It's nothing fancy, more like my first experiment. I have tried to find solution to this error for several hours and red a lot of articles, so I am very sorry, if I ask you something, that has been already answered, I haven't found it.
All I have found and tried:
update R Studio (no effect)
try to first write the file into some temporary dir and then load it back (no effect)
Thank you for your help!

Related

R-Shiny - Change file by SelectInput and re-run code

I am working on a shiny app. I am sorry if I am unclear, but I am at the very beginning with shiny.
Basically, I have a long list of functions that are sourced into the shiny app before starting the server and the ui.
All these functions rely on a single database which is imported in the source file through an readRDS call.
source("calculations.R")
dash <- shinyApp(
server = function(input, output) {
output$element1 <- renderText({db1$var1[[1]]})
...
},
ui = shinyUI(fluidPage(
dashboardPage(
options = list(sidebarExpandOnHover = TRUE),
header = dashboardHeader(title="Title"),
sidebar = dashboardSidebar(minified = TRUE, collapsed = TRUE),
body = dashboardBody(
fluidRow(
column(width=8, box(width=12, title="Hello", valueBox(width=6, color="yellow", textOutput("element1")))
...
),
),
controlbar = dashboardControlbar(selectInput(inputId='selectfile','Select File',choice = list.files('folder/'))),
title = "DashboardPage"
)))
)
dash
The structure of the source file is pretty much the following:
db1 <- readRDS("folder/file1.rds")
Now, what I am trying to do is to let the user select another file from the folder (let's say, file2.rds) through the selectInput in the dashboard.
This should be following by:
replacing the old db1 with the new one (i.e., db1 <- readRDS("folder/file2.rds"))
update all the following code in the calculations.R file (I've created a calculations2.R file, which is a copy of calculations.R, but without the first line of code which read the file and put into the db1 object, as it would overwrite the new file)
update the output variables in the server
update the data in the UI.
I've tried several solution. Currently I am stuck with the following (in which calculations2.R contains the same code of calculations.R, without the db1 <- readRDS("folder/file1.rds") call at the beginning of the file):
shinyApp(
server = function(input, output) {
db1 <- reactive({readRDS(file.path("folder",input$selectfile))})
observeEvents(input$selectfile, {source("calculations2.R")})
output$element1 <- renderText({db1$var1[[1]]})
...
},
However, everytime I select another file from the selectInput, it get me an error from the functions in the calculations2.R, as if db1 was not appropriately loaded.

How to integrate code into a shiny app and upload files?

I'm new to shiny and I would like your advice on a requirement that I have at my office. I apologize in advance for not providing more information or code at the moment.
I have currently coded a R script that does the following:
Import 7 excel files with read_excel:
File 1 will go to dataset 1
File 2 will go to dataset 2
File 3,4,5,6,7 will go to dataset 3 by using lapply
Does a whole lot of data cleaning, formatting, parsing and ordering
Merges everything together and creates a final excel and txt files with specific formatting
Im requiring a shiny web app that:
Provides 3 different upload boxes for the user. One for each type of file (1 / 2 / 3,4,5,6,7)
Internally saves the uploaded files so the code i already have can use them for its processing
Lets the user download the 2 output files made by my code to the computer
If possible, show a log window on the app so the user can know if something goes wrong with the code execution
Datasets visualization is not required
I might be asking a lot. I will appreciate if you just can give me some lights in how i can start working on this. I would like not to modify my current code, if possible (can i have shiny acquire the files, and call my code so it can process them?)
Here is a minimal example showing uploading files, processing them, and downloading them.
For simplicity I've used 3 inputs and a single output.
If you want to notify a user that something has happened, you can use showNotification()
library(shiny)
ui <- fluidPage(
#File Upload Boxes
fileInput("myfileinput_1", label = "Upload File 1", accept = ".csv"),
fileInput("myfileinput_2", label = "Upload File 2", accept = ".csv"),
fileInput("myfileinput_3", label = "Upload File 3", accept = ".csv"),
#Button
actionButton("mybutton", label = "Process Uploaded Files"),
#Table Showing Processed Data
tableOutput("mytable"),
#Download Buttons
downloadButton("myfiledownload", label = "Download Processed File")
)
server <- function(input, output, session) {
#A reactive dataframe to store our outputfile
reactives <- reactiveValues(
df_output = NULL
)
#Runs when button is pressed
observeEvent(input$mybutton, {
#Check that all 3 files are selected before loading
if(!is.null(input$myfileinput_1) & !is.null(input$myfileinput_2) & !is.null(input$myfileinput_3)) {
#Load input files
df_input_1 <- read.csv(input$myfileinput_1$datapath)
df_input_2 <- read.csv(input$myfileinput_2$datapath)
df_input_3 <- read.csv(input$myfileinput_3$datapath)
#Use input to create an output (we're just using a simple example)
reactives$df_output <- data.frame(
input = c("Input 1", "Input 2", "Input 3"),
rows = c(nrow(df_input_1), nrow(df_input_2), nrow(df_input_3))
)
showNotification("Files Successfully Processed", type = "message")
} else {
showNotification("Ensure all three files are selected before loading", type = "error")
}
})
#Table Output
output$mytable <- renderTable({
reactives$df_output
})
#Download handler
output$myfiledownload <- downloadHandler(
filename = "mydata.csv",
content = function(file) {write.csv(reactives$df_output, file, row.names = FALSE)}
)
}
shinyApp(ui, server)

How to create a text input that receives several words separated by commas in a shiny app?

So I have a shiny app and a text input that receives a single word which serves as input for a function, it looks like this in the UI:
textInputAddon(inputId="taxa",addon=icon("search"),
label=tags$h4(tags$strong("Enter the name of the taxonomic group:")),placeholder="Example: Cetacea")
Then in the server the word submited in the input is used to download a tsv file, and I render it like this:
taxaInput <- reactive({grades(input$taxa)})
output$downloadData <- downloadHandler(
filename = function() {
paste(input$taxa, ".tsv")
},
content = function(file) {
shiny::withProgress(
message=paste0("Downloading and annotating dataset for ",input$taxa), detail='This may take several minutes',
value=0,
{
shiny::incProgress(1/10)
Sys.sleep(1)
shiny::incProgress(4/10)
write_tsv(taxaInput(), file)
}
)
}
)
The "grades()" function is my user made function and I can onlye use it to download the file searching for one single word. What I want is to be able to search to put something like this in the input:
Word1,Word2,Word3
In a simples R script I used to replace the word for a vector:
group<-c(Word1,Word2,Word3)
But in the shiny app I'm not being able to
Thanks for any response in advance
You can use unlist(strsplit(input$taxa, ",")). However you are better off using selectInput() with multiple = T if the taxa choices are exhaustive. That way you'll won't need strsplit and also you have complete control on what words are entered.
Anyways, here's the way with strsplit -
library(shiny)
shinyApp(
ui = fluidPage(
textInput("words", "Enter Words"),
verbatimTextOutput("test")
),
server = function(input, output, session) {
output$test <- renderPrint({
words <- unlist(strsplit(input$words, ",")) # get words separated by ','
paste0(words, "_", seq_along(words)) # some random function
})
}
)
App snapshot -

How to use local .txt files in a Shiny App

Hi all this is my first question, so I hope the format is correct.
I'm looking to create a R shiny app that calls on all the .txt files that that are within the parameters set by the user, merges those .txt files, and produces a word cloud.
The app located here https://lukaszsowinski.shinyapps.io/WC-app/ crashes once it is opened, although it works on my local computer. I'm almost sure it has to do with the way I'm writing in my wd(), data files, and .txt files as they were giving me problems before I was able to finally published. This is the error I'm getting
2017-08-12T01:17:22.742107+00:00 shinyapps[204302]: Error in loadWorkbook(file) :
2017-08-12T01:17:22.742109+00:00 shinyapps[204302]: Cannot find /home/shiny/WC-app/WordMappingInfo.xlsx
Here is the ines of code that I'm not sure where my error is.
library(rsconnect)
rsconnect::deployApp('C:/Users/Lukasz Sowinski/Desktop/WC-app')
server <- function(input, output, server)
{
textframe <- read.xlsx("C:/Users/Lukasz Sowinski/Desktop/WC-app/WordMappingInfo.xlsx", 1)
schooldata <- list (
"Num" = textframe$Num[!is.na(textframe$Num)],
"SchoolName" = C(textframe$SchoolName),
"Path" = c(
"C:/Users/Lukasz Sowinski/Desktop/WC-app/texts/Queens College.txt",
"C:/Users/Lukasz Sowinski/Desktop/WC-app/texts/Lehman College.txt",
"C:/Users/Lukasz Sowinski/Desktop/WC-app/texts/Denison University.txt",
"C:/Users/Lukasz Sowinski/Desktop/WC-app/texts/St Johns University.txt",
"C:/Users/Lukasz Sowinski/Desktop/WC-app/texts/Rutgers University.txt"
),
"Students" = textframe$Students[!is.na(textframe$Students)],
"Tuition" = textframe$Tuition[!is.na(textframe$Tuition)],
"Program" = textframe$Program[!is.na(textframe$Program)]
)
Here is the some of the cod where I call up the data as needed based on user input.
if (schooldata$Program[i] == input$selection)
{
if (temptext == 0)
{
temptext <- schooldata$Path[i]
temptext.1 <- readLines(temptext)
mastertext.1 = temptext.1
}
temptext <- schooldata$Path[i]
temptext.1 <- readLines(temptext)
mastertext.1 <- rbind(mastertext.1, temptext.1)
}
I've also tried using pathways
"./WC-app/WordMappingInfo.xlsx"
"~/WC-app/WordMappingInfo.xlsx"
That I found in similar questions but neither work.
Any help would be tremendously appreciated. Thank you
Have you tried with shinyFiles CRAN packages extension?
In the ui.R file
shinyUI(bootstrapPage(
shinyFilesButton('files', label='File select', title='Please select a file', multiple=FALSE)
))
In the server.R file
shinyServer(function(input, output) {
shinyFileChoose(input, 'files', root=c(root='.'), filetypes=c('', 'txt'))
})

R: Shiny, how to use renderTable to replace reactiveTable?

I am trying to load multiple text files (each has a string of characters) into Shiny and I found a very nice tutorial to begin with:
https://gist.github.com/jcheng5/4050398
The code is shown below:
ui.R
shinyUI(pageWithSidebar(
headerPanel("File input test"),
sidebarPanel(
fileInput("files", "File data", multiple=TRUE)
),
mainPanel(
tableOutput("filetable")
)
))
server.R
shinyServer(function(input, output) {
output$filetable <- reactiveTable(function() {
if (is.null(input$files)) {
# User has not uploaded a file yet
return(NULL)
}
input$files
})
})
The issue I have is that the result got a warning: reactiveTable is deprecated. Please use renderTable instead. Besides that, the code does work well.
However, after I replaced reactiveTable with renderTable, I got an error message: Error: no applicable method for 'xtable' applied to an object of class "function"
Any idea how to replace reactiveTable with renderTable correctly? Thanks a lot!

Resources