I´m new using R and I would like to call from a script to another using source() function and by the way,passing some parameters. This are my two R scripts:
Server.r
library(shiny)
shinyServer(function(input, output) {
#esta funcion guarda el csv cargado
filedata <- reactive({
infile <- input$datafile
if (is.null(infile)) {
return(NULL)
}
read.csv(infile$datapath, sep = ";")
})
filedata1 <- reactive({
infile1 <- input$datafile1
if (is.null(infile1)) {
return(NULL)
}
read.csv(infile1$datapath, sep = ";")
})
observeEvent(input$do, {
source("C:/.../app1.R", params=filedata, params=filedata1, local = TRUE)
})
app.r
...
csv1=read.csv("filedata", sep = ";")
csv2=read.csv("filedata1", sep = ";")
...
I don´t know how to send both .csv inserted (filedata, filedata1) from Server.r to app.r.
Thank you very much in advance
Related
I have an .xlsx file with multiple sheets which I am uploading to my Shiny app using fileInput having id "file". My objective is to load a sheet using a string detect, that is if I have 3 sheets in random order named "apple", "orange" and "banana", I would like to load the "apple" sheet using string match from the list of sheets. So far I am not being able to get the list of sheets as I keep running into the error when I try to extract the sheet names using excel_sheets using readxl package-
Warning: Error in : `path` does not exist: ‘C:\Users\AppData\Local\Temp\Rtmp6dWPYS/0b16b05aa5a58cc1d1261369/0.xlsx’
The relevant server code is as follows -
sheet_names <- reactive({
if (!is.null(input$file)) {
return(excel_sheets(path = input$file))
} else {
return(NULL)
}
})
apple_data <- reactive({
req(input$file)
inFile <- input$file
if(is.null(inFile))
return(NULL)
file.rename(inFile$datapath,
paste(inFile$datapath, ".xlsx", sep=""))
p<-read_excel(paste(inFile$datapath, ".xlsx", sep=""),
sheet = sheet_names() [str_detect(sheet_names(), regex("(apple)"))]
})
After tweaking around with various functions, I eventually found a way to do it using openxlsx. Sharing the solution below -
wb<- reactive({
req(input$file)
inFile<- input$file
wb<-loadWorkbook(paste(inFile$datapath, ".xlsx", sep=""))
})
sheetnames <- reactive({
req(input$file)
if (is.null(input$file))
return(NULL)
sheet_names<-wb()$sheet_names
})
apple_data <- reactive({
req(input$file)
inFile <- input$file
if(is.null(inFile))
return(NULL)
file.rename(inFile$datapath,
paste(inFile$datapath, ".xlsx", sep=""))
p<-read_excel(paste(inFile$datapath, ".xlsx", sep=""),
sheet = sheet_names() [str_detect(sheet_names(), regex("(apple)"))]
})
The issue in the OP's code is that the function sheet_names() is using the logical vector str_detect(sheet_names(), regex("(apple)")) as input. Instead it would be
...
sheet = sheet_names()[str_detect(sheet_names(), regex("(apple)"))])
...
You can try this code -
library(shiny)
library(readxl)
ui <- fluidPage(
fileInput('file', 'Input'),
tableOutput('table')
)
server <- function(input, output) {
apple_data <- reactive({
req(input$file)
inFile <- input$file
if(is.null(inFile)) return(NULL)
sheetnames <- excel_sheets(path = inFile$datapath)
read_excel(inFile$datapath, sheet = grep('apple', sheetnames, value = TRUE))
})
output$table <- renderTable(apple_data())
}
shinyApp(ui, server)
I want to make my server.R file to load the csv file of a binary matrix when it starts.
library(shiny)
server <- function(input, output) {
#this aint loading
df <- read.csv("starGraphAdjMatrix.csv",
header = TRUE,
sep = ",",
quote='"')
#output$loadedMat -> output$loadedMat
output$loadedMat <- renderTable({
# input$file1 will be NULL initially. After the user selects
# and uploads a file, head of that data file by default,
# or all rows if selected, will be shown.
#falsy value if empty
req(input$file1)
# when reading semicolon separated files,
# having a comma separator causes `read.csv` to error
tryCatch(
{
df <- read.csv(input$file1$datapath,
header = TRUE,
sep = ",",
quote='"')
df$X <- NULL
},
error = function(e) {
# return a safeError if a parsing error occurs
stop(safeError(e))
}
)
return(df)
},
rownames = FALSE, colnames = FALSE)
}
Full code including ui.R and the starGraphAdjMatrix here:
https://github.com/andandandand/fixCSVLoad
Not sure if this is what you were after:
library(shiny)
server <- function(input, output) {
output$contents <- renderTable({
if (is.null(input$file1$datapath)) {
dpath <- "starGraphAdjMatrix.csv"
} else {
dpath <- input$file1$datapath
}
read.csv(dpath)
}, rownames = FALSE, colnames = FALSE)
}
In my below example of a simple shiny app i recently created, im currently trying to include also the possibility of downloading a data frame that is created from the results. I mention here part of the server.R script in order to not make a huge post:
shinyServer(function(input, output) {
table_options<- list(lengthMenu = list(c(5,10,15,20),
c('5','10', '15', '20')), pageLength = 15, ordering=TRUE,
class = 'cell-border stripe',dom ='t',scrollX = TRUE,
fixedColumns = list(leftColumns = 2, rightColumns = 1))
inTable <- reactive({# upload a tsv file
inFile <- input$file1
if (is.null(inFile))
return(NULL)
read.table(inFile$datapath,header=input$header,
sep="\t",stringsAsFactors = FALSE)
}) #END REACTIVE
rv <- reactiveValues()
rv$data <- NULL # to further use it into the observeEvent below
observeEvent(input$goButton, {
df <- inTable()
# some data manipulation with df...
if(input$repo_option=="mimic"){
# some functions here that result to a data frame named final dat
rv$data <- final.dat
rv$data
}
else if(input$repo_option=="reverse"){
# similar procedure...
rv$data <- final.dat
rv$data
}
})
output$contents <- DT::renderDataTable({
expr=DT::datatable(rv$data, options=table_options,
extensions ='FixedColumns',selection="none")
})
output$downloadData <- downloadHandler(
filename = function() { paste("input$file1", ".csv", sep=",") },
content = function(file) {
write.csv(rv$data,file)
}
)
})
My main issue is that, although the output$contents works fine in the app, when i press the download button from the ui.R server (not posted here for simplicity), the download "pop-up" window appears, but the saving does not work. Thus, i suspect that is something wrong with the code in the downloadHandler function, but any ideas or help ?
I am new to R programming. When I execute my shiny app code, I get the error "Error in func() : object 'file3' not found". Any suggestions on how to resolve this? Below is the server.R code where I have the error:
library(shiny)
shinyServer(function(input, output) {
reactive ({
if(is.null(input$file1)) return(NULL)
fl1 <- paste("file:///",input$file1,sep='')
if(is.null(input$file2)) return(NULL)
fl2 <- paste("file:///",input$file2,sep='')
file1 <- read.table(fl1,sep=',',header=TRUE)
file2 <- read.table(fl2,sep=',',header=TRUE)
library(sqldf)
options(gsubfn.engine = "R")
file3 <- sqldf('SELECT * FROM file2 UNION ALL SELECT * FROM file1')
})
output$text1 <- renderTable({ file3 })
})
I am answering based on the code provided, since you reference input$xx, I assume that you have a ui.R file :-). Also if your files are uploaded files you will need to handle them using shiny::observeEvent, otherwise input$file1 and input$file2 will always be NULL.
You also should ensure that the UI object with inputID = "text1" is defined as a dataTable output rather than a textOutput. So something like this: shiny::dataTableOutput("text1"). This will ensure that your input is parsed correctly.
I have also fixed some of your styling to make you code more readable. See google R Style Guide.
You can try the following, taking into account the above:
library(shiny)
library(sqldf)
options(gsubfn.engine = "R")
shinyServer(function(input, output) {
getData <- reactive ({
if(is.null(input$file1)) return(NULL)
fl1 <- paste("file:///", input$file1, sep = '')
if(is.null(input$file2)) return(NULL)
fl2 <- paste("file:///", input$file2, sep='')
file1 <- read.table(fl1, sep = ',', header = TRUE)
file2 <- read.table(fl2, sep = ',', header = TRUE)
file3 <- sqldf('SELECT * FROM file2 UNION ALL SELECT * FROM file1')
return(file3)
})
output$text1 <- shiny::renderDataTable({ getData() })
})
I hope this helps. You may also want to try using DT::renderDataTable instead of shiny::renderDataTable
I am trying to load an excel file and display the summary. The file is loading without any errors but not displaying anything.
Here is my code
ui.R
library(shiny)
shinyUI(pageWithSidebar(
headerPanel("Analysis"),
sidebarPanel(wellPanel(fileInput('file1', 'Choose XLSX File',
accept=c('sheetName', 'header'), multiple=FALSE))),
mainPanel(
tabsetPanel(
tabPanel("Tab1",h4("Summary"), htmlOutput("summary"))
)))
server.R
library(shiny)
shinyServer(function(input, output) {
dataset = reactive({
infile = input$file1
if (is.null(infile))
return(NULL)
infile_read = read.xlsx(infile$datapath, 1)
return(infile_read)
})
output$summary <- renderPrint({
summary = summary(dataset())
return(summary)
})
outputOptions(output, "summary", suspendWhenHidden = FALSE)
})
I haven't tested this, but it looks like you're not actually returning anything from dataset(). Change the function to:
dataset = reactive({
infile = input$file1
if (is.null(infile))
return(NULL)
read.xlsx(infile$datapath, 1)
})
When you do infile_read = read.xlsx(infile$datapath, 1), you're reading the file into infile_read but then you're not actually returning it. Reactives work just look any R function really. Try running this:
f <- function() x <- 10
f()
You should see that f() doesn't return anything. All it's doing is making an assignment that goes nowhere. To actually return 'hello' you would do:
f <- function() {
x <- 'hello'
x
}
Or just:
f <- function() 'hello'