I’m trying to format the output file from Vissim simulation to csv file. So I have 2 Fileinputs:
FileInput 1 is for formatting the FZP file to CSV file, it can be uploaded multiple file but for now it can only upload 2 at max, but later on I would like the FileInput 1 can process more than 2 files.
FileInput 2 is for merging the CSV file after converting the FZP file, because 1 run of VISSIM simulation can be multiple FZP files, so if I want to merge 2 runs or more I would like to use the FileInput 2 for merging it.
And my problem is in FileInput 1 because when I upload 2 files FZP it’s not causing an error, but when I only upload 1 file FZP it cause an error ‘Subscript Out of Bound’ even I already made a condition where the FileInput 1 in index 2 is Null then create new dataframe. Because, I’m trying to access individual file from the multiple uploaded file for calculating average of attributes in the FZP file by attribute called ‘VEHTYPE’.
So, how would I solve this?
#UI
library(shiny)
library(data.table)
shinyUI(fluidPage(
titlePanel("File Input"),
sidebarLayout(
sidebarPanel(
tags$hr(),
fileInput("file1",
"Choose FZP files",
multiple = TRUE),
fileInput("file2",
label="Upload multiple CSVs here",
multiple = TRUE),
uiOutput("column_1"),
downloadButton("download", "Filter Table"),
downloadButton("download1", "Aggregate Table")
),
mainPanel(
uiOutput("tb")
))
))
#Server
library(shiny)
library(dplyr)
library(plyr)
library(data.table)
shinyServer(function(input, output) {
data1 <- reactive({
inFile <- input$file1
if (is.null(inFile)) {
return(NULL)
} else {
inFile %>%
rowwise() %>%
do({
df <- fread(input$file1[[1, 'datapath]]', skip="t;", sep = ";", header=T, stringsAsFactor = F)
})
}
})
data2 <- reactive({
inFile <- input$file1
if (is.null(input$file1[[2, "datapath"]])) {
subData <- data1()
df <- subData[0,]
df
#data1()
} else {
inFile %>%
rowwise() %>%
do({
df <- fread(input$file1[[2, 'datapath']], skip="t;", sep = ";", header=T, stringsAsFactor = F)
})
}
})
output$column_1 <- renderUI({
if (is.null(data1())) {
return(NULL)
} else {
selectInput("column1", "Feature selection:", names(data1()))
}
})
average1 <- reactive({
#Processing data1
subsetData1 <- data1()
calAvg1 <- subsetData1[, c("VEHTYPE",input$column1)]
calAvg1 <- aggregate(calAvg1[, ncol(calAvg1)], list(VEHTYPE = calAvg1$VEHTYPE), mean)
total <- sum(calAvg1[, ncol(calAvg1)])/length(calAvg1$VEHTYPE)
dfTotal1 <- data.frame("Total", total)
names(dfTotal1) <- c("VEHTYPE", input$column1)
newDF1 <- rbind(calAvg1, dfTotal1)
})
average2 <- reactive({
#Processing data2
subsetData2 <- data2()
if(is.data.frame(subsetData2) && nrow(subsetData2)==0){
subsetData2
}else{
calAvg2 <- subsetData2[, c("VEHTYPE",input$column1)]
calAvg2 <- aggregate(calAvg2[, ncol(calAvg2)], list(VEHTYPE = calAvg2$VEHTYPE), mean)
total <- sum(calAvg2[, ncol(calAvg2)])/length(calAvg2$VEHTYPE)
dfTotal2 <- data.frame("Total", total)
names(dfTotal2) <- c("VEHTYPE", input$column1)
newDF2 <- rbind(calAvg2, dfTotal2)
}
})
finalDF <- reactive({
if(is.data.frame(average2()) && nrow(average2())==0){
average1()
}else{
final <- rbind(average1(), average2())
#average2()
}
#Merge all dataframe
#finalDF <- rbind(average1(), average2())
})
data3 <- reactive({
req(input$file2) ## ?req # require that the input is available
multiFile <- input$file2
df <- rbindlist(lapply(multiFile$datapath, fread),
use.names = TRUE, fill = TRUE)
as.data.frame(df)
return(df)
})
output$original <- renderDataTable({
data1()
})
output$filterData <- renderTable({
finalDF()
})
output$multiData <- renderTable({
data3()
})
output$download <- downloadHandler(
filename = function(){
paste("data-", Sys.Date(), ".csv", sep = "")
},
content = function(file){
write.csv(get_table(), file,row.names = F)
}
)
output$download1 <- downloadHandler(
filename = function(){
paste("data-", Sys.Date(), ".csv", sep = "")
},
content = function(file){
write.csv(data3(), file,row.names = F)
}
)
output$tb <- renderUI({
tabsetPanel(tabPanel("Original Data", dataTableOutput("original")),
tabPanel("Filter Data", tableOutput("filterData")),
tabPanel("Aggregate Data", tableOutput("multiData"))
)
})
})
FZP files look more or less like this:
$VISION
* File: Y:\03_Studentische Arbeiten\VT\IDP\Windu\Test Simulation\test1.inpx
* Comment:
* Date: 03.08.2017 09:32:43
* PTV Vissim: 9.00 [04]
*
* Table: Vehicles In Network
*
* SIMSEC: SimSec, Simulation second (Simulation time [s]) [s]
* NO: No, Number (Number of the vehicle)
* LANE\LINK\NO: Lane\Link\No, Lane\Link\Number (Unique number of the link or connector)
* LANE\INDEX: Lane\Index, Lane\Index (Unique number of the lane)
* POS: Pos, Position (Distance on the link from the beginning of the link or connector) [m]
* POSLAT: PosLat, Position (lateral) (Lateral position at the end of the time step. Value range 0 - 1: 0: at the right lane edge 0.5: middle of the lane 1: at the left lane edge)
* EMISSIONSCO2: EmissionsCO2, Emissions CO2 (Quantity of carbon monoxide [grams / sec])
* EMISSIONSNOX: EmissionsNOx, Emissions NOx (Quantity of nitrogen oxides [grams / sec])
* FUELCONSUMPTION: FuelConsumption, Fuel consumption (Fuel consumption [US liquid gallon])
* INQUEUE: InQueue, In queue (Returns if the vehicle is in queue. Queue is defined by speed and headway treshholds. (see queue definition))
* NUMSTOPS: NumStops, Number of stops (Number of stops (cumulative): all situations in which a vehicle comes to a standstill (speed = 0), except stops at PT stops and in parking lots)
* SPEED: Speed, Speed (Speed at the end of the time step) [km/h]
* VEHTYPE: VehType, Vehicle type (Select Vehicle type from the list box)
*
* SimSec; No; Lane\Link\No; Lane\Index; Pos; PosLat; EmissionsCO2; EmissionsNOx; FuelConsumption; InQueue; NumStops; Speed; VehType
*
$VEHICLE:SIMSEC;NO;LANE\LINK\NO;LANE\INDEX;POS;POSLAT;EMISSIONSCO2;EMISSIONSNOX;FUELCONSUMPTION;INQUEUE;NUMSTOPS;SPEED;VEHTYPE
0.50;1;1;1;0.80;0.50;;;;0;0;41.70;100
0.60;1;1;1;1.96;0.50;;;;0;0;41.90;100
0.70;1;1;1;3.13;0.50;;;;0;0;42.16;100
0.80;1;1;1;4.31;0.50;;;;0;0;42.50;100
0.90;1;1;1;5.49;0.50;;;;0;0;42.91;100
1.00;1;1;1;6.69;0.50;;;;0;0;43.39;100
1.10;1;1;1;7.90;0.50;;;;0;0;43.92;100
1.20;1;1;1;9.13;0.50;;;;0;0;44.44;100
1.30;1;1;1;10.37;0.50;;;;0;0;44.96;100
1.40;1;1;1;11.63;0.50;;;;0;0;45.48;100
1.50;1;1;1;12.90;0.50;;;;0;0;45.99;100
1.60;1;1;1;14.18;0.50;;;;0;0;46.49;100
1.70;1;1;1;15.48;0.50;;;;0;0;47.00;100
1.80;1;1;1;16.79;0.50;;;;0;0;47.50;100
Error
Warning: Error in [[: subscript out of bounds
Stack trace (innermost first):
117: [[.data.frame
116: [[
115: fread
114: overscope_eval_next
113: do.rowwise_df
112: do
111: function_list[[k]]
110: withVisible
109: freduce
108: _fseq
107: eval
106: eval
105: withVisible
104: %>%
103: <reactive:data2>
92: data2
91: <reactive:average>
80: average
79: renderTable
78: func
77: origRenderFunc
76: output$filterData
1: shiny::runApp
I think that the problem is in the assignment of the file to the data frame, I fixed a bit the code there.
Try changing the server code in the following way and let me know whether it works.
shinyServer(function(input, output) {
data1 <- reactive({
inFile <- input$file1
if (is.null(inFile)) {
return(NULL)
} else {
inFile %>%
rowwise() %>%
do({
df <- fread(input$file1$datapath, skip="t;", sep = ";", header=T, stringsAsFactor = F)
})
}
})
data2 <- reactive({
inFile <- input$file1
if (is.null(inFile)) {
return(NULL)
} else {
inFile %>%
rowwise() %>%
do({
df <- fread(input$file2$datapath, skip="t;", sep = ";", header=T, stringsAsFactor = F)
})
}
})
output$column_1 <- renderUI({
if (is.null(data1())) {
return(NULL)
} else {
selectInput("column1", "Feature selection:", names(data1()))
}
})
To convert .fzp files to .txt or .csv just use DOS command prompt.
You can navigate to your folder and use the following syntax:
ren *.fzp *.txt
or
ren *.fzp *.csv
after that, follow the steps on this page reading from folder
and use read.csv with "skip= " to read your files.
Related
I am creating an app to allow user to upload two excel files and carry over the comments one to the other one, then to download the merged file. The downloadhandler is not working when I tried to run it on the published server, however it running properly locally in rstudio. Any thoughts/suggestions?
library(plyr)
library(dplyr)
library(tidyr)
library(readxl)
library(xlsx)
library(openxlsx)
ui <- fluidPage(
br(),
titlePanel("Excel File Merging Tool"),
br(),
br(),
sidebarLayout(
sidebarPanel(
fileInput("file1", label = h3("Upload New File"), multiple = FALSE, buttonLabel = "Browse", placeholder = "No file selected"),
fileInput("file2", label = h3("Upload Old File"), multiple = FALSE, buttonLabel = "Browse", placeholder = "No file selected"),
actionButton("actionMerge", label = "Merge Uploaded Files"),
hr(),
downloadButton('downloadData', 'Download Merged File')
),
mainPanel(
)
)
)
#Defined Funtions
read_excel_allsheets <- function(filename, tibble = FALSE) {
sheets <- readxl::excel_sheets(filename)
x <- lapply(sheets, function(X) readxl::read_excel(filename, sheet = X))
if(!tibble) x <- lapply(x, as.data.frame)
names(x) <- sheets
x
}
server <- function(input, output) {
getData <- eventReactive(input$actionMerge, {
inFile1 <- input$file1
if (is.null(inFile1)){
return(NULL)
} else {
mydata1= read_excel_allsheets(inFile1$datapath)}
inFile2 <- input$file2
if (is.null(inFile2)){
return(NULL)
} else {
mydata2= read_excel_allsheets(inFile2$datapath)}
wb <- createWorkbook()
#find tabs not in old file
newSheets <- (names(mydata1))[which(!(names(mydata1)) %in% (names(mydata2)))]
if (length(newSheets) > 0){
for (n in newSheets)
{
mydata6 <- bind_rows(mydata1[n])
addWorksheet(wb, sheetName = names(mydata1[n]))
writeData(wb, names(mydata1[n]), mydata6)
}}
for (i in names(mydata1)){
for (j in names(mydata2)){
if (i == j ){
if ((nrow(as.data.frame(mydata1[i]))) == 0 | (nrow(as.data.frame(mydata2[j]))) == 0 )
{
mydata6 <- bind_rows(mydata1[i])
addWorksheet(wb, sheetName = names(mydata1[i]))
writeData(wb, names(mydata1[i]), mydata6)
}
else {
if (ncol(bind_rows(mydata1[i])) == ncol(bind_rows(mydata2[j])) )
{
mydata6 <- bind_rows(mydata1[i])
addWorksheet(wb, sheetName = names(mydata1[i]))
writeData(wb, names(mydata1[i]), mydata6)
}
else {
# validate(
# column_mismatch(mydata1[i], mydata2[j])
# )
drop_in_key <- c("Earliest data creation time", "Latest data update time", "Timestamp of last save in clinical views", "Date time value from the source file name",
"Lowest Date of Rec, Pg, Inst or Subj", "Record Minimum Created Datetime Stamp", "Record Maximum Updated Datetime Stamp", "Accessible to Jreview Timestamp")
mydatax0 = bind_rows(mydata1[i])
mydatax = bind_rows(mydata1[i])[,!(names(bind_rows(mydata1[i])) %in% drop_in_key)]
mydatanew <- mydatax %>% unite(col="Key", 1:(ncol(mydatax)-1), sep=";", remove=FALSE)
mydatanew$Newflag <- "New"
mydatanew0 = mydatanew %>% select(Key, Newflag)
mydatanew1 = bind_cols(mydatanew0,mydatax0)
mydatay0 = bind_rows(mydata2[j])
mydatay = bind_rows(mydata2[j])[,!(names(bind_rows(mydata2[j])) %in% drop_in_key)]
mydataold <- mydatay %>% unite(col="Key", 1:(ncol(mydatay)-1), sep=";", remove=FALSE)
mydataold$Oldflag <- "Old"
mydataold0 <- mydataold %>% select(Oldflag, Key)
mydataold1 <- bind_cols(mydataold0,mydatay0)
mydataold2 = select(mydataold1, Key, Oldflag, (ncol(bind_rows(mydata1[i]))+3):((ncol(mydataold1))))
mydata3 <- merge(x=mydatanew0, y=mydataold2, by="Key", all=TRUE)
mydata4 <- subset(mydata3, Newflag == "New")
mydata5 <- merge(x=mydatanew1, y=mydata4, by="Key", all.y=TRUE)
drop <- c("Key", "Newflag.x", "Oldflag", "Newflag.y")
mydata6 = mydata5[,!(names(mydata5) %in% drop)]
addWorksheet(wb, sheetName = names(mydata1[i]))
writeData(wb, names(mydata1[i]), mydata6)
}}}
else
NULL
}
}
saveWorkbook(wb, file = "aaa.xlsx" , overwrite = TRUE)
})
output$downloadData <- downloadHandler(
filename = function() {
paste0(input$file2, ".xlsx")
},
content = function(file) {
file.copy("aaa.xlsx", file)
})
}
shinyApp(ui = ui, server = server)```
Here's a toy shiny app that provides a solution that is safe for concurrent users. All operations are done on either (a) temporary files that shiny controls, or (b) in the directory of one of these temp files, using tempfile to create the new filename. Both of those assure new-file uniqueness, so no filename collisions. (I believe shiny's method is temporary directories under a temp-directory, at least that's what I'm seeing in my dev env here. So ... seemingly robust.)
The some_magic_function function is mostly because I didn't want to generate an example with openxlsx and sample datas and such, mostly my laziness. For your code, remove all of the if (runif... within the tryCatch and replace with whatever you need, ensuring your code ends by returning the filename with the new data (or updated) data.
... but keep the tryCatch! It will ensure that the function always returns "something". If all code succeeds, then the function will return the filename with new/updated data. If something goes wrong, it returns a class "error" string that can be used to communicate to the user (or otherwise react/recover).
Last thing, though it's just icing on my cupcake here: I use the shinyjs package to disable the 'merge' and 'download' buttons until there is valid data. Frankly, once the two file-selection inputs have something set, the "merge" button will likely never be disabled. However, if there's ever a problem during the merge/update, then the download button will be disabled (until a merge/update happens without error).
library(shiny)
library(shinyjs)
# a naive function that just concatenates the files, first removing
# the header row from the second file
some_magic_function <- function(f1, f2) {
# put the output file in the same directory as 'f2'
d <- dirname(f2)
if (!length(d)) d <- "."
output_file <- tempfile(tmpdir = d, fileext = paste0(".", tools::file_ext(f2)))
tryCatch({
if (runif(1) < 0.2) {
# purely for StackOverflow demonstration
stop("Something went wrong")
} else {
# add your stuff here (and remove the runif if/else)
writeLines(c(readLines(f1), readLines(f2)[-1]), output_file)
output_file # you must return this filename
}
}, error = function(e) e)
# implicitly returning the output_file or an error (text with class 'error')
}
shinyApp(
ui = fluidPage(
shinyjs::useShinyjs(),
titlePanel("Tool"),
sidebarLayout(
sidebarPanel(
fileInput("file1", label = "File #1", multiple = FALSE, placeholder = "No file selected"),
fileInput("file2", label = "File #2", multiple = FALSE, placeholder = "No file selected"),
actionButton("btn", label = "Merge uploaded files"),
hr(),
downloadButton("dnld", "Download merged file")
),
mainPanel(
tableOutput("tbl"),
hr(),
verbatimTextOutput("bigtext")
)
)
),
server = function(input, output, session) {
# start with neither button enabled
for (el in c("btn", "dnld")) shinyjs::disable(el)
# disable the 'merge' button until both files are set
observeEvent({
input$file1
input$file2
}, {
req(input$file1, input$file2)
shinyjs::toggleState("btn", isTRUE(file.exists(input$file1$datapath) && file.exists(input$file2$datapath)))
})
# this is the "workhorse" of the shiny app
newfilename <- eventReactive(input$btn, {
req(input$file1, input$file2)
some_magic_function(input$file1$datapath, input$file2$datapath)
})
# prevent the download handler from being used if the new file does not exist
observeEvent(newfilename(), {
cond <- !is.null(newfilename()) &&
!inherits(newfilename(), "error") &&
file.exists(newfilename())
shinyjs::toggleState("dnld", cond)
})
output$dnld <- downloadHandler(
filename = function() paste0("merged_", input$file2),
content = function(f) {
file.copy(newfilename(), f)
}
)
# some sample output, for fun
output$tbl <- renderTable({
req(newfilename(),
!inherits(newfilename(), "error"),
file.exists(newfilename()))
read.csv(newfilename(), nrows = 10, stringsAsFactors = FALSE)
})
output$bigtext <- renderText({
if (inherits(newfilename(), "error")) {
# if we get here then there was a problem
as.character(newfilename())
} else "(No problem)"
})
}
)
Notes:
shiny::req is supposed to ensure the data has something useful and "truthy" in it (see shiny::isTruthy). Normally it is good with detecting nulls, NA, empty variables, etc ... but it "passes" something that has class "error", perhaps counter-intuitive. That's why I had to be a little more explicit with conditions in some of the reactive blocks.
One impetus for having the merge/update functionality within an external not-shiny-requiring function (some_magic_function here) is that it facilitates testing of the merge functionality before adding the shiny scaffolding. It's difficult to test basic functionality when one is required to interact with a browser for every debugging step of basic functionality.
I am trying to write my first Shiny App that reads a PDF file, extracts tables and saves it into Excel document.
I am failing to produce suitable code. So far I have:
1) For UI
shinyUI(fluidPage(
titlePanel("CMM Report"),
sidebarPanel(
fileInput("file", "Upload Report")
),
downloadButton("dl", "Download")
))
2) For Server
library(shiny)
library (tabulizer)
library(writexl)
shinyServer(function(input, output) {
data <- reactive({
file1 <- input$file
if(is.null(file1)){return()}
file1 <- ExtractTable (file1)
})
## Download
output$dl <- downloadHandler(
filename = function() { "ae.xlsx"},
content = function(file) {write_xlsx(data, path = file)}
)
})
I am not sure If I need to put the code for extracting table in a function and where to call the function, to make it work. Any help REALLY appreciated.
The data file of the example is from here
report <- "http://www.stat.ufl.edu/~athienit/Tables/Ztable.pdf"
Function to extract data
ExtractTable <- function (report){
lst <- extract_tables(report, encoding="UTF-8")
# Delete blank columns
lst[[1]] <- lst[[1]][, -3]
lst[[2]] <- lst[[2]][, -4]
# Bind the list elements
table <- do.call(rbind, lst)
table <- as.data.frame(table[c(2:37, 40:nrow(table)), ],
stringsAsFactors=FALSE) # ...w/o obsolete rows
# Take over colnames, cache rownames to vector
colnames(table) <- table[1, ]
rn <- table[2:71, 1]
table <- table[-1,-1] # and bounce them out of the table
# Coerce to numeric
table <- as.data.frame(apply(table[1:70,1:10], 2,
function(x) as.numeric(as.character(x))))
rownames(table) <- rn
return(table)
}
Could you try:
shinyServer(function(input, output) {
data <- reactive({
file1 <- input$file
if(is.null(file1)){return()}
ExtractTable(file1$datapath) # $datapath was missing
})
## Download
output$dl <- downloadHandler(
filename = function() { "ae.xlsx"},
content = function(file) {write_xlsx(data(), path = file)} # parentheses () were missing
)
})
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)
}
I have an rshiny app and i'm trying to download a csv file from the app after it is edited. I followed the examples online, but the download button isn't working. I know the button is fine, its copied directly from the rshiny documentation. I assume the error is server side
server <-function(input,output){# Combine the selected variables into a new data frame
#output$value <- renderPrint({
# str(input$GimmeCSV[2,2])
output$table.preview <- renderTable({
inFile <- input$GimmeCSV
preview <- read.csv(inFile$datapath, header=TRUE, sep=",")
return(head(preview)) # undo Table can be modified
})
output$table.output <- renderTable({
inFile <- input$GimmeCSV
tbl <- read.csv(inFile$datapath, header=TRUE, sep=",")
#return(head(tbl)) # undo Table can be modified
################^ preview of csv table################
#look up how to extract the columns with no name present(something numerical)
#After that is figured out calculating the rest of those values will be a snap
#tbl <- read.csv(inFile$datapath, header=TRUE, sep=",")
#below is temporary file path only used for testing purposes, the above read.csv is the true pooba
#STANDARDS!!!
solar <- tbl$solar
temp <- tbl$temp
ws <- tbl$ws
#return(head(solar))
Ktemp <-temp + 273
ktemp <-temp + 273
#lol
if ((input$Shape) == shape_select[1]){
Len <- (input$diacone)
Height <- (input$hgtcone)
Width <- 0
} else {if((input$Shape) == shape_select[2]){
Len <- (input$diasphere)
Height <- 0
Width <- 0
}
else
Len <- (input$lenprism)
Height <- (input$hgtprism)
Width <- (input$widprism)
}
r <-Len/2
#return(r)
if (Len >=0.037){ # Absorptivity from Luke Miller
Abs <- 0.615
} else {if (Len <= 0.02225 ){Abs <-0.689
} else Abs <- 0.68 }
#works!
Emm <-0.97
#TOTALLY ARBITURARY SURFACE AREA VALUES BASED ON WHAT I KNOW!
ConeA <- (pi*r*r) + (sqrt((Height*Height)+(r*r))) # area of cone
SphereA <- (4*pi*(r*r)) #area of sphere
PrismA <- ((2*Len*Width) + (2*Height*Len) +( 2*Height*Width))
#return(PrismA)
#WORKS
#Deciding which surface area area to calculate
if ((input$Shape) == shape_select[1]){
SA <-ConeA
} else {if((input$Shape) == shape_select[2]){SA <- SphereA}
else SA <-PrismA}
#WOEKS!!!!!!!
#return(SA)
#Temporary placeholder values for PSA
PSA <- SA
SB <- 5.67E-08 # Stephan Boltzman constant
eskyclear <- 0.72 + (0.005*temp)
CC <- 0.5 #Cloud over 0 - 1
esky <- eskyclear + CC*(1 - eskyclear - (8/ktemp)) #IR emissivity from sky
Aradsky <- SA/2 #surface area projected to the sky
Aradground <- SA/2 # surface area projected to the ground
K3 <- esky^(1/4)
K2 <- 4 * SB * Emm * (esky)^(3/4)
K4 <- 4 * SB * Emm
K5 <- 0.6/(0.5*Len)
hc <- 0.6
com1 <- (Abs * solar) + (K2 * (Aradsky/PSA) * K3 * Ktemp^4) + (K4 * (Aradground/PSA) * Ktemp^4) + (K5 * PSA * Ktemp) + (hc*SA*Ktemp) + 2.48*0
com2 <- (4180 * 0) + ((Ktemp^3) * K2 * (Aradsky/PSA)) + (K4 * (Aradground/PSA) *(Ktemp^3)) + (hc*SA) + (K5*PSA)
#works!
Sol <- com1 / com2
modeltemp <- Sol - 273
max <- max(modeltemp)
min <- min(modeltemp)
mydata <- data.frame( Daily_Temp = temp, Solar_Radiation = solar, Body_Temperature = modeltemp, stringsAsFactors = FALSE)
return(mydata)
output$downloadData <- downloadHandler(
filename = function() { paste(input$inFile, '.csv', sep='') },
content = function(file) {
write.csv(mydata, file)
}
)
})
} #app goes here lol
shinyApp(ui, server)
}
Any sugestions are appreciated
I rearranged your code a bit and created 2 reactiveValues at the beginning of the server function.
In an observeEvent, you wait until the fileInput-Button (input$GimmeCSV) is clicked, it reads the csv then and assigns it to the reactive value inputFile. Then you can access this value directly in both renderTable outputs, as you would load the csv twice in your example. If the file is not too big, it shouldnt be a problem, but its not necessary.
The downloadHandler goes outside the renderTable function and takes the input argument (input$inFile), which is used to name the output file. For the content, the second reactiveValue is used, where the data was assigned in output$table.output.
library(shiny)
ui <- fluidPage(
sidebarLayout(
sidebarPanel(
fileInput("GimmeCSV", "Upload a CSV", multiple = F),
textInput("inFile", "Name for Output"),
downloadLink("downloadData", "Download")
),
mainPanel(
tableOutput("table.preview"),
tableOutput("table.output")
)
)
)
server <-function(input,output){
inputFile <- reactiveValues(file = NULL)
outputFile <- reactiveValues(file=NULL)
observeEvent(input$GimmeCSV, {
inFile <- input$GimmeCSV
data <- read.csv(inFile$datapath, header=TRUE, sep=";")
inputFile$file <- data
})
output$table.preview <- renderTable({
head(inputFile$file)
})
output$table.output <- renderTable({
tbl <- inputFile$file
outputFile$file <- tbl
tbl
})
output$downloadData <- downloadHandler(
filename = function() {
paste(input$inFile, '.csv', sep='')
},
content = function(file) {
write.csv(outputFile$file, file)
}
)
}
shinyApp(ui, server)
Hope it helps.
I have .txt file and .xlsx file which will be uploaded into shiny.
The .txt upload is fine, the builtin progress bar shows perfect progress.
But in the case of .xlsx file upload I have merging operation doing inside reactive element so it is not coinciding with the actual progress. (Progress bar always finishes ahead of the task)
I can use pbapply, but then again I have to monitor them through command line, this is not what I am looking for.
I am very much interested in making the built in progress bar in connection with the entire upload process inside the reactive element. How can I do that.
This is my program.
ui.R
shinyUI(fluidPage(
titlePanel("Uploading Files"),
sidebarLayout(
sidebarPanel(
fileInput('file1', 'Choose first file to upload',
accept = c(
'text/csv',
)
),))sidebarLayout(
sidebarPanel(
fileInput('file1', 'Choose second file to upload',
accept = c(
'.xlsx'
)
)
)))
server.R
shinyServer(function(input, output) {
a <- reactive({
fileinput1 <- input$file1
if (is.null(fileinput1))
return(NULL)
read.table(fileinput1$datapath, header = TRUE, col.names = c("Experiment","Mesocosm","Hour","Nphy","Cphy","CHLphy","Nhet","Chet","Ndet","Cdet","DON","DOC","DIN","DIC","AT","dCCHO","TEPC","Ncocco","Ccocco","CHLcocco","PICcocco","PAR","Temperature","Salinity","CO2atm","u10","DICflux","CO2ppm","CO2mol","pH"))
#a$Chla <- a$CHLphy + a$CHLcocco #Add new columns as per observation data
#a$PON <- a$Nphy + a$Nhet + a$Ndet + a$Ncocco
})
#Upload Observation Data
b <- reactive({
#xlfile <- list.files(pattern = "*.xlsx")
fileinput2 <- input$file2
if (is.null(fileinput2))
return(NULL)
xlfile <- fileinput2$datapath
wb <- loadWorkbook(xlfile)
sheet_ct <- wb$getNumberOfSheets()
for( i in 1:sheet_ct) { #read the sheets into 3 separate dataframes (mydf_1, mydf_2, mydf3)
print(i)
variable_name <- sprintf('mydf_%s',i)
assign(variable_name, read.xlsx(xlfile, sheetIndex=i))
}
colnames(mydf_1) <- names(mydf_3)
colnames(mydf_2) <- names(mydf_3)
full_data <- rbind(mydf_1[-1,],mydf_2[-1,],mydf_3[-1,]) #making one dataframe here
b <- lapply(full_data,function(x) as.numeric(x))
})
})
How can I achieve this ?
You have some problems in your code but in theory you can create progress bar to the top of the browser:
observe({
fileinput2 <- input$file2
if (is.null(fileinput2))
return(NULL)
withProgress(message = 'Downloading file', value = 0, {
#xlfile <- list.files(pattern = "*.xlsx")
xlfile <- fileinput2$datapath
wb <- loadWorkbook(xlfile)
sheet_ct <- wb$getNumberOfSheets() # this will be used in progressbar
for( i in 1:sheet_ct) { #read the sheets into 3 separate dataframes (mydf_1, mydf_2, mydf3)
print(i)
variable_name <- sprintf('mydf_%s',i)
assign(variable_name, read.xlsx(xlfile, sheetIndex=i))
incProgress(1/sheet_ct, detail = paste("Sheet:", sheet_ct,"Dowloaded"))
}
colnames(mydf_1) <- names(mydf_3)
colnames(mydf_2) <- names(mydf_3)
full_data <- rbind(mydf_1[-1,],mydf_2[-1,],mydf_3[-1,]) #making one dataframe here
b <- lapply(full_data,function(x) as.numeric(x))
})
})
})
More info: http://shiny.rstudio.com/articles/progress.html