I have the following code which runs perfectly!. However, I want to restrict the archiving of the data by pushing the "Export All" button to only once per day. I tried to use if statements and not successful. Another fact is the code is running over Shiny-Server pro and different browser sessions will be created. Any Suggestions?.
library(shiny)
library(shinyBS)
library(XLConnect)
library(lubridate)
cData <- '
Candidate,Party,Province,Age,Gender
"L, L",NDP,Quebec,22,Female
"M, M",Bloc Quebecois,Quebec,43,Female
"M, S",Bloc Quebecois,Quebec,34,Female
"S, D",NDP,Quebec,,Female
"S, L",NDP,Quebec,72,Female
"F, H",Liberal,British Columbia,71,Female
"T, N",NDP,Quebec,70,Female
"S, J",Liberal,Ontario,68,Female
"R, Francine",NDP,Quebec,67,Female
"D, Patricia",Conservative,Ontario,66,Female
"S, Joy",Conservative,Manitoba,65,Female
"W, Alice",Conservative,British Columbia,64,Female
"O, Tilly",Conservative,New Brunswick,63,Female
"A, Diane",Conservative,Alberta,63,Female
"D, Linda",NDP,Alberta,63,Female
"B, Carolyn",Liberal,Ontario,62,Female
"N, Peggy",NDP,Ontario,61,Female
"M, Irene",NDP,Ontario,61,Female
"S, Jinny",NDP,British Columbia,60,Female
"F, Judy",Liberal,Newfoundland,60,Female
"C, Jean",NDP,British Columbia,60,Female
"D, Libby",NDP,British Columbia,59,Female
"Y, Lynne",Conservative,Saskatchewan,59,Female
"D, Anne",NDP,Quebec,58,Female
"M, Elizabeth",Green,British Columbia,58,Female
"M, Joyce",Liberal,British Columbia,58,Female
"F, Kerry",Conservative,British Columbia,57,Female
"B, Lois",Conservative,Ontario,57,Female
"B, Marj",NDP,Quebec,57,Female
"C, Joan",Conservative,Alberta,56,Female
"C, Olivia",NDP,Ontario,55,Female
"M, Cathy",Conservative,British Columbia,55,Female
"F, Diane",Conservative,Ontario,55,Female
"L, Helene",NDP,Quebec,54,Female
"G, Nina",Conservative,British Columbia,54,Female
"H, Carol",NDP,Ontario,54,Female
"P, Gail",Conservative,Prince Edward Island,53,Female
"T, Susan",Conservative,Ontario,53,Female
"Y, Wai",Conservative,British Columbia,52,Female'
con <- textConnection(cData)
cEl <- read.csv(con, header=TRUE, stringsAsFactors = FALSE)
cEl$votes <- round(runif(nrow(cEl), min=500, max=15000))
TheDataDF <- cEl
ui <- fluidPage(
titlePanel("Archive Data Post on Stack Overflow"),
# Button and Alert, we use the alert to control only onetime Archive
sidebarLayout(
sidebarPanel(
bsAlert("alert"),
downloadButton("ArchiveBtn", "Archive All")
),
# Show the table
mainPanel(
DT::dataTableOutput('TheData')
)
)
)
server <- function(input, output,session) {
output$TheData <- DT::renderDataTable(DT::datatable(TheDataDF,options = list(pageLength = 25,scrollX = TRUE),
rownames = FALSE,class = 'cell-border stripe')
%>% formatStyle(c(2:ncol(TheDataDF)),
color = styleInterval(55, c('red', 'black'))))
output$ArchiveBtn <- downloadHandler(
filename = function() {
paste("ArchiveData-", ymd(Sys.Date()), ".xlsx", sep="")
},
content = function(file) {
fname <- paste(file,"xlsx",sep=".")
wb <- loadWorkbook(fname, create = TRUE)
#creating sheets within the Excel workbook
createSheet(wb, name = "The Arc Data")
#writing into sheet within the Excel workbook :
writeWorksheet(wb, TheDataDF, sheet = "The Arc Data", startRow = 1, startCol = 1)
saveWorkbook(wb)
file.rename(fname,file)
# Create the message for the complition of the archive
createAlert(session, "alert", "exampleAlert", style="success",title = "Archive Complete!",
content = "Data archived", append = FALSE)
}
)
}
# Run the application
shinyApp(ui = ui, server = server)
Related
This script outputs excel spreadsheets of different region. However, since I included a column "Later", changed the corresponding template to also include the column "Later" and increased the number on this line "df <- subset(clist[,c(1:18, 20:29)" from 28 to 29 (given the increased column). The output on the column "group" has come back with its content, but with quotation mark and some instance with CHAR(10).
Is there anyway I can edit this script to have column "group" outcome its content without the quotation marks. Please help!! help! I have struggled with this since. See script below
NB changes made to the original script are as follows
inclusion of later in the sqlcode
changing the df <- subset(clist[,c(1:18, 20:28)" to df <- subset(clist[,c(1:18, 20:29)
Changing the second df <- subset(clist[,c(1:17, 19:28)] to df <- subset(clist[,c(1:18, 20:29)]
#####Constants#####
requiredpackages <- c("XLConnect", "RPostgreSQL", "svDialogs", "getPass")
reqpackages <- function(requiredpackages){
for( i in requiredpackages ){
if( ! require( i , character.only = TRUE ) ) {
install.packages( i , dependencies = TRUE )
library( i , character.only = TRUE )
}
}
}
# set the version to 1.0.5
packageurl <- "https://cran.r-project.org/src/contrib/Archive/XLConnect/XLConnect_1.0.5.tar.gz"
install.packages(packageurl, repos=NULL, type="source")
library(XLConnect)
library(RPostgreSQL)
library(svDialogs)
library(getPass)
source("N:/Ana/Code/Analysiss/Rational/R SQL working/postgresql-avd.R")
#####Retrieve data from analysis server#####
sqlcode <- paste("SELECT concat_ws(';',datacompletion,sortprovider) as datacompletion,ba,outstandingdata,provider,summary,
m,m_hos,m_sur,m_for,m_dob,ed,
bkhos,delhos,
pregnancy,b_d,
b,b_na,
group,groupsw,later,estimated,
screening,date,screening2,
booking,city,use,con,water
FROM common.etl_chasing
where ((date::text like '%",tperiod,"%' or date::text like '%",cperiod,"%')
and (anomalygroup like '%Down%' or group like '%Edwards%' or group like '%Patau%'))
or eddfyear like '%", fperiod,"%' or cleanyear like '%", cperiod, "%'", sep='')
con <- createConnection()
clist <- dbGetQuery(con, sqlcode)
dbDisconnect(con)
#####Create new folder on PID drive to output chasing lists to#####
dirname <- paste("P:/Data/Antenatal/Testing/", Sys.Date(),sep='')
dir.create(dirname)
#####Export CSV of all data#####
write.csv(clist,paste(dirname,"/masterlist.csv",sep=''))
#####Copy template for all individual providers#####
sortproviders <- unique(clist$sortprovider)
inpath <- "P:/Data/National/Antenatal/Template17b.xlsx"
for (i in seq_along(sortproviders)) {
outpath <- paste(dirname,"/",sortproviders\[i\]," AN LIST.xlsx", sep='')
file.copy(from = inpath, to = outpath)
}
#####Populate templates for individual providers#####
swpatterns <- c("68 - ", "70 - ", "72 - ", "73 - ", "84 - ", "93 - ", "94 - ", "95 - ", "96 - ", "99 - ")
#grepl(paste(swpatterns, collapse = "|"), sortproviders\[1\])
#otherpatterns \<- c("72 - ", "96 - ", "73 - ", "93 - ", "94 - ", "72 - ", "99 - ")
#swsortproviders \<- unique(grep(paste(swpatterns, collapse = "|"), sortproviders, value = TRUE))
#restsortprividers \<- unique(grep(paste(otherpatterns, collapse = "|"), sortproviders, value = TRUE))
for (i in seq_along(sortproviders)) {
outpath \<- paste(dirname,"/",sortproviders\[i\]," AN LIST.xlsx", sep='')
if (grepl(paste(swpatterns, collapse = "|"), sortproviders\[i\]) == FALSE) {
df <- subset(clist[,c(1:18, 20:29)], sortprovider == sortproviders[i])
dfformulacol <- as.vector(df$anomalygroup)
df <- cbind(df, df)
XLConnect::writeWorksheetToFile(outpath, df, sheet = "trust list", startRow = 4, header = FALSE, styleAction = XLC$"STYLE_ACTION.NONE")
wb <- loadWorkbook(filename = outpath, create = FALSE)
for (j in seq_along(dfformulacol)) {
setCellFormula(wb, "trust list", j+3, 18, dfformulacol[j])
}
for (k in seq_along(dfformulacol)) {
setCellFormula(wb, "trust list", k+3, 45, dfformulacol[k])
}
saveWorkbook(wb)
rm(wb)
} else {
df <- subset(clist[,c(1:18, 20:29)], sortprovider == sortproviders[i])
df <- cbind(df, df)
XLConnect::writeWorksheetToFile(outpath, df, sheet = "trust list", startRow = 4, header = FALSE, styleAction = XLC$"STYLE_ACTION.NONE")
wb <- loadWorkbook(filename = outpath, create = FALSE)
saveWorkbook(wb)
rm(wb)
}
rm(df)
xlcFreeMemory()
}
#####################################
The following R script is a simple GUI using gWidgets.
I was wondering why this code does not save the selected values by user in gcheckboxgroup.
#### Clear the Global Environment:
rm(list=ls())
library(rattle)
library(RGtk2)
library(gWidgets)
library(tcltk)
library(lubridate)
w <- gwindow("checkbox example")
gp <- ggroup(container=w)
codes = c(
"1000 F",
"0100 Q",
"0010 M",
"0001 s")
cbg <- gcheckboxgroup(codes, cont=w)
selected_codes <- paste(svalue(cbg))
ff <- function(h,...)
selected_codes <- svalue(cbg)
obj_run <- gbutton("Run", container=w, handler = ff)
Thanks for jverzani's comment.
However, that was not the solution.
Actually, by clicking the Run button in GUI, we have the selected_code is the R memory. But it can not be saved as it is inside the function/handler. So, we need to save (write) it in a file (.txt for example) using this code:
rm(list=ls())
library(rattle)
library(RGtk2)
library(gWidgets)
library(tcltk)
library(lubridate)
w <- gwindow("checkbox example")
gp <- ggroup(container=w)
codes = c(
"1000 F",
"0100 Q",
"0010 M",
"0001 s")
cbg <- gcheckboxgroup(codes, cont=w)
obj_run <- gbutton("Run", container=w, handler = function (h ,...){
selected_codes <- paste0(svalue(cbg))
write(selected_codes, file = "selected_codes.txt",
ncolumns = if(is.character(selected_codes)) 1 else 1,
append = FALSE, sep = " ")
})
Try this, it is less hassle:
library(gWidgets2)
w <- gwindow("checkbox example")
gp <- ggroup(container=w)
codes = c(
"1000 F",
"0100 Q",
"0010 M",
"0001 s")
g <- ggroup(cont=w, horizontal=FALSE)
cbg <- gcheckboxgroup(codes, cont=g)
selected_codes <- paste(svalue(cbg))
ff <- function(h,...) {
selected_codes <<- svalue(cbg)
}
obj_run <- gbutton("Run", container=g, handler = ff)
(You may have had issues due to the containers.)
I need to take the data returned from timevis, but these data are returned with one hour less than the data entered. I have tried changing the R time zone and the server too, but that has not solved the problem.
here's a simple example of what I'm trying to do:
ui<-fluidPage(
mainPanel(
timevisOutput("gantt"),
tableOutput("return"),
actionButton("btn","btn")
)
)
server <- function(input, output, session) {
data <- data.frame(
id = 1:4,
content = c("Item one" , "Item two" ,"Ranged item", "Item four"),
start = c("2016-01-10 00:00:00", "2016-01-11T00:00:00.000Z", "2016-01-20", "2016-02-14 15:00:00"),
end = c(NA , NA, "2016-02-04", NA),
group =c(1,1,2,2)
)
output$gantt<-renderTimevis({
timevis(data= data,
groups = data.frame(id = 1:4, content = c(" 1", " 2", " 3", " 4")),
options = list(editable = list(add=FALSE, remove=TRUE, updateTime= TRUE, updateGroup=TRUE, overrideItems=TRUE), align = "left"))
})
observeEvent(input$btn,{
output$return<-renderTable(
print(input$gantt_data)
)
})
}
shinyApp(ui, server)
The result of input$gantt_data returned is this:
id content start group end
1 1 Item one 2016-01-09T23:00:00.000Z 1 <NA>
2 2 Item two 2016-01-10T23:00:00.000Z 1 <NA>
3 3 Ranged item 2016-01-19T23:00:00.000Z 2 2016-02-03T23:00:00.000Z
4 4 Item four 2016-02-14T14:00:00.000Z 2 <NA>
First of all: Since you use mixed date formats, the second event is not displayed correctly. In my example below, I corrected that.
Since the timeline itself contains the dates in the correct time zone, it's just an issue of the object returned by input$gantt_data. You can manually correct that by first converting it to a POSIXct object and then displaying it in your desired timezone:
library(timevis)
ui<-fluidPage(
mainPanel(
timevisOutput("gantt"),
tableOutput("return"),
actionButton("btn","btn")
)
)
server <- function(input, output, session) {
data <- data.frame(
id = 1:4,
content = c("Item one" , "Item two" ,"Ranged item", "Item four"),
start = c("2016-01-10 00:00:00", "2016-01-11 00:00:00.00", "2016-01-20", "2016-02-14 15:00:00"),
end = c(NA , NA, "2016-02-04", NA),
group =c(1,1,2,2)
)
output$gantt<-renderTimevis({
timevis(data= data,
groups = data.frame(id = 1:4, content = c(" 1", " 2", " 3", " 4")),
options = list(editable = list(add=FALSE, remove=TRUE, updateTime= TRUE, updateGroup=TRUE, overrideItems=TRUE), align = "left"))
})
observeEvent(input$btn,{
output$return<-renderTable({
dat <- input$gantt_data
dat$start <- format(as.POSIXct(input$gantt_data$start, format = "%Y-%m-%dT%H:%M:%S", tz = "UTC"), tz="Europe/Berlin")
dat$end <- format(as.POSIXct(input$gantt_data$end, format = "%Y-%m-%dT%H:%M:%S", tz = "UTC"), tz="Europe/Berlin")
print(dat)
})
})
}
shinyApp(ui, server)
I'm trying to generate a .xlsx file through the Openxlsx package with a reactive name and header inside file (the input variables are "ASL.1" and "Year.1"). The object to be saved in the file is the reactive table "tab_1 ()", that is generated by the app without any problems, but when I try to download it the name that is generated by the browser (Chrome) is not (i.e.) "Tab_1_TOSCANA_2015".xlsx" but "download_tab_1", the outputId of the button "download" associated, and nothing is generated. I do not understand where the problem is, since I checked other similar examples with Openxlsx and I do not see errors in my script; if I try to write a .csv file using the "write.csv" command everything works.
The script is here: https://drive.google.com/drive/folders/1dSI9qWgQyShjXjkJ2B6COuWzuWZie5IP?usp=sharing
The App (this is just a small part) is
https://cerimp-open-data.shinyapps.io/Malprof/
require(shiny)
require(dplyr)
require(reshape2)
require(stringr)
require(shinythemes)
require(ggplot2)
require(openxlsx)
require(leaflet)
require(RColorBrewer)
require(rgdal)
require(rgeos)
require(maptools)
load("dati.RData")
#### UI ####
ui <- fluidPage(
theme = shinytheme("spacelab"),
titlePanel("Indice"),
navlistPanel(
#### Tab I ####
tabPanel(title = "Tab. I Tassi per ASL di competenza e Sesso",
h1(textOutput(outputId = "tab_1_text"), style = "font-size:100%"),
fluidRow(column(3, selectInput(inputId = "ASL.1",
label = "Territorio",
choices = list("TOSCANA", "ASL CENTRO","ASL NORD-OVEST","ASL SUD-EST"),
selected = "Toscana",
multiple = FALSE)),
column(3, selectInput(inputId = "Anno.1",
label = "Anno di manifestazione",
choices = as.list(unique(malprof$Anno)),
selected = max(malprof$Anno),
multiple = FALSE))),
fluidRow(column(2, downloadButton(outputId = "download_tab_1",
label = "Scarica i dati"))),
div(tableOutput(outputId = "tab_1"), style = "font-size:80%")
),
#### Fig 1 ####
tabPanel(title = "Fig. 1 Andamento delle denunce INAIL e delle segnalazioni Malprof",
h1(textOutput(outputId = "fig_1_text"), style = "font-size:100%"),
fluidRow(column(3, selectInput(inputId = "ASL.fig.1",
label = "Territorio",
choices = list("TOSCANA", "ASL CENTRO","ASL NORD-OVEST","ASL SUD-EST"),
selected = "Toscana",
multiple = FALSE))),
div(plotOutput(outputId = "fig.1"), style = "font-size:80%")
)
)
#### SERVER ####
server <- function(input, output) {
fargs <- list(big.mark=".", decimal.mark=",") #parametri per la formattazione dei numeri nelle tabelle
annoUltimo <- max(malprof$Anno)
rg <- filter(malprof, ASL == "TOSCANA")
no <- filter(malprof, ASL == "ASL NORD-OVEST")
se <- filter(malprof, ASL == "ASL SUD-EST")
ce <- filter(malprof, ASL == "ASL CENTRO")
#### Tabella I - Distribuzione di frequenza delle segnalazioni di MP e dei relativi tassi per 100.000 abitanti suddivisi per ASL di competenza e Sesso ####
selezioneASL.1 <- reactive({switch(input$ASL.1,
"TOSCANA" = rg,
"ASL CENTRO" = ce,
"ASL NORD-OVEST" = no,
"ASL SUD-EST" = se)})
tab.1 <- reactive({
pop <- popTosc %>% filter(Anno == input$Anno.1) %>%
dcast(EXASL ~ SEX, drop = T, fill = 0, fun.aggregate = sum, value.var = "N") %>%
filter(!is.na(EXASL))
mp <- selezioneASL.1() %>% filter(Anno == input$Anno.1) %>%
dcast(EXASL ~ sesso_lav, drop = T, fill = 0, fun.aggregate = length, value.var = "Anno")
tab <- pop %>% inner_join(mp, by = c("EXASL" = "EXASL")) %>%
mutate(T_F = round((F.y/F.x)*100000, 1),
T_M = round((M.y/M.x)*100000, 1)) %>%
select(EXASL, F.x, M.x, F.y, M.y, T_F, T_M)
tab.tot <- c("TOTALE", sum(tab$F.x), sum(tab$M.x), sum(tab$F.y), sum(tab$M.y), round((sum(tab$F.y)/sum(tab$F.x))*100000, 1), round((sum(tab$M.y)/sum(tab$M.x))*100000, 1))
tab <- rbind(tab, tab.tot)
tab$F.x <- as.numeric(tab$F.x)
tab$M.x <- as.numeric(tab$M.x)
tab$F.y <- as.numeric(tab$F.y)
tab$M.y <- as.numeric(tab$M.y)
tab$T_F <- as.character(tab$T_F)
tab$T_M <- as.character(tab$T_M)
tab <- rename(tab, "EXASL" = EXASL, "Pop. F" = F.x, "Pop. M" = M.x, "Segn. F" = F.y, "Segn. M" = M.y, "Tasso - F" = T_F, "Tasso - M" = T_M)
tab
})
output$tab_1_text <- renderText(paste0("Distribuzione di frequenza delle segnalazioni di MP e dei relativi tassi per 100.000 abitanti suddivisi per ASL di competenza e Sesso - ", input$ASL.1, ", ", input$Anno.1, "."))
output$tab_1 <- renderTable({tab.1()},
display=c("s","s","d","d","d","d","s","s"),
spacing="s",
align = 'lcccccc',
na="--", format.args=fargs)
output$download_tab_1 <- downloadHandler(
filename = function() {
paste("Tab_1_", input$ASL.1, "_", input$Anno.1, ".xlsx", sep = "")
},
content = function(file) {
wb <- createWorkbook()
addWorksheet(wb, sheetName = "Dati", gridLines = TRUE)
intestazione <- paste0("Distribuzione di frequenza delle segnalazioni di MP e dei relativi tassi per 100.000 abitanti suddivisi per ASL di competenza e Sesso - ", input$ASL.1, ", ", input$Anno.1, ".")
writeData(wb, 1, x = intestazione)
writeDataTable(wb, sheet = 1, startRow = 3, x = tab.1(), colNames = TRUE)
saveWorkbook(wb, file)
}
)
}
# Run the application
shinyApp(ui = ui, server = server)
I have been working through what sounds like the same problem. It was caused by a problem the openxlsx package being accessed by the downloadHandler (Shiny). No amount of fixing permissions or ensuring the package was in the correct folder worked. As far as we could figure out its a problem with the Shiny download handler interacting with openxlsx.
In the end I fixed this by saving a local version temp of the XLSX and then referencing this in the downloadHandler.
Move this section (inside the downloadHandler) to outside of the download handler:
addWorksheet(wb, sheetName = "Dati", gridLines = TRUE)
intestazione <- paste0("Distribuzione di frequenza delle segnalazioni di MP e dei relativi tassi per 100.000 abitanti suddivisi per ASL di competenza e Sesso - ", input$ASL.1, ", ", input$Anno.1, ".")
writeData(wb, 1, x = intestazione)
writeDataTable(wb, sheet = 1, startRow = 3, x = tab.1(), colNames = TRUE)
saveWorkbook(wb, file)
Then inside the handler use a version of this:
output$downloadData <- downloadHandler(
filename = function(){paste0(intestazione,".xlsx")},
content = function(file) {
file.copy(filename,file)
#file.rename(fname,file)
}
)
I think I get it working by simply referencing file in the saveWorkbook function inside the download handler...
This is working with openxlsx package and Shiny downloadHandler :
output$quick_export <- downloadHandler(
filename = "my export.xlsx",
content = function(file) {
wb <- createWorkbook()
addWorksheet(wb, "Cars")
x <- mtcars[1:6, ]
writeData(wb, "Cars", x, startCol = 2, startRow = 3, rowNames = TRUE)
saveWorkbook(wb, file, overwrite = TRUE)
}
)
I am trying to build a shiny app where extract_text and extract_table functions from R tabulizer package are used. But the problem is in an instance the results from the first file I upload remains, i.e. if I upload a pdf file the desired results appear, but even if I upload a new file the results don't change unless I stop and start a new instance. Here is my server.R code-
shinyServer(function(input,output,session) {
fund<-reactive({
inFile <- input$file1
if (is.null(inFile))
{return(NULL)} else {
rr<-extract_text(inFile$datapath, pages =2)
e1<-extract_tables(inFile$datapath, pages =1)
e2<-extract_tables(inFile$datapath, pages =2)
rr<-gsub("\r\n", " ", rr)
ss<-unlist(strsplit(rr, "Total & WAR:"))
gr<-grep("Reverse Repo With Bank", ss)
if (length(gr)>=1) {
sk<-gsub("(?<=[\\s])\\s*|^\\s+|\\s+$", "", ss[gr], perl=T)
sn<-unlist(strsplit(sk, " ", fixed=T))
grp<-grep("Limited", sn)
dm<-matrix(nrow=length(grp), ncol=4)
party<-c()
for (i in 1:length(grp)){
dm[i,]<-sn[(grp[i]+1):(grp[i]+4)]
party[i]<-paste(sn[(grp[i]-2):(grp[i])],sep="", collapse=" ")
}
dm<-as.data.frame(dm)
names(dm)<-c("Amount", "Rate", "DealDate", "MaturityDate" )
dm$PartyName<-party
dm$Tenure<-rep("", times=nrow(dm))
dm<-dm[,c(5:6,1:4)]
dn<-data.frame(PartyName="Product Name : Reverse Repo with Bank", Tenure="", Amount="", Rate="", DealDate="", MaturityDate="")
dnn<-data.frame(PartyName="Total & WAR:", Tenure="", Amount="", Rate="", DealDate="", MaturityDate="")
dm<-rbind(dn,dm,dnn)
}
if (length(e1)>1) {
l1<-dim(e1[[1]])[1]
l2<-dim(e1[[2]])[1]
m<-c(l1,l2)
e<-e1[[which(m==max(m))]]
} else {e=e1[[1]]}
gop<-grep("Party Name", e[,1], fixed=T)
e<-e[-(1:(gop-1)),]
e[,3]<-gsub("(?<=[\\s])\\s*|^\\s+|\\s+$", "", e[,3], perl=T)
if (ncol(e)==4){
ss<-strsplit(e[,3], " ")
s1<-sapply(ss, function(x) x[1])
s2<-sapply(ss, function(x) x[2])
sss<-strsplit(e[,4], " ")
s1s<-sapply(sss, function(x) x[1])
s2s<-sapply(sss, function(x) x[2])
e<-cbind(e[,1:2],s1,s2,s1s,s2s)
} else if (ncol(e)==5) {
sss<-strsplit(e[,5], " ")
s1s<-sapply(sss, function(x) x[1])
s2s<-sapply(sss, function(x) x[2])
e<-cbind(e[,1:4],s1s,s2s)
}
d<-rbind(e[-1,],e2[[1]][-1,])
d<-as.data.frame(d)
colnames(d)<-c("PartyName", "Tenure", "Amount", "Rate", "DealDate", "MaturityDate")
if (length(gr)>=1){
d<-rbind(d,dm)
}
row.names(d)<-1:nrow(d)
d$Rate<-as.numeric(as.character(d$Rate))
w<-which(d$Rate>7)
d<-d[-w,]
d$IncomeType<-rep(NA, nrow(d))
d$Rate[is.na(d$Rate)]<-0
levels<-c(-1,1,5,7)
labels<-c("Invalid","Low Income", "Medium Income")
d$IncomeType<-cut(d$Rate, levels, labels)
d$Period<-as.Date(d$MaturityDate, format="%d/%m/%Y")-Sys.Date()
d$Period[is.na(d$Period)]<-1
levels1<-c(-50,-1,1,15,30,5000)
labels1<-c("Already Matured", "Within 1 Day", "Within 2 to 15 Days", "Within 16 to 30 Days", "More than 1 Month")
d$MaturityType<-cut(as.numeric(d$Period), levels1, labels1)
m<-grep("Product Name : Commercial Paper", d[,1], fixed=T)
d<-d[-m,]
g1<-grep("Product Name",d[,1], fixed=T)
name<-d[g1,1]
name<-as.character(name)
name<-sapply(strsplit(name,": "), "[", 2)
g2<-grep("Total & WAR",d[,1], fixed=T)
w<-which(d[,1]=="Product Name : Call Borrowing with Bank")
if (length(w)>=1){
d<-d[-(g1[which(g1==w)]:g2[which(g1==w)]),]
name<-name[-which(g1==w)]
g1<-grep("Product Name",d[,1], fixed=T)
g2<-grep("Total & WAR",d[,1], fixed=T)
}
Product<-c()
for (i in 1: length(g1)) {
Product[(g1[i]):(g2[i])]<-name[i]
}
d$Product<-Product
d<-d[!(is.na(d$DealDate)|d$DealDate==""),]
d$Amount<-as.numeric(gsub(",", "", d$Amount))
Remaining<-as.Date(d$MaturityDate, format="%d/%m/%Y")-Sys.Date()
d$Remaining<-ifelse(is.na(Remaining)!=TRUE, Remaining, "ON CALL")
d<-d[order(d$IncomeType,d$Product),]
d<-d[,c(1,10,3,4,7,5,6,11)]
d$DealDate<-as.character(d$DealDate)
d$MaturityDate<-as.character(d$MaturityDate)
d$Period<-as.Date(d$MaturityDate, format="%d/%m/%Y")-Sys.Date()
d$Period[is.na(d$Period)]<-1
levels1<-c(-5000,0,1,15,30,5000)
labels1<-c("Already Matured", "Matures Next Day", "In Between 2 to 15 Days", "In Between 16 to 30 Days", "More than 1 Month")
d$MaturityType<-cut(as.numeric(d$Period), levels1, labels1)
d1<-d[,1:8]
d1<-d1[order(d$IncomeType,d$Product),]
rate<-sum(as.numeric(d1$Amount)*as.numeric(d1$Rate)/sum(as.numeric(d1$Amount)))
d1<-as.data.frame(apply(d1, 2, function(x) gsub("^\\s+|\\s+$", "", x)), stringsAsFactors = F)
d1$MaturityDate[is.na(d1$MaturityDate)]<-""
d1[(nrow(d1)+1),]<-c("Total","",sum(as.numeric(d1$Amount)),rate, rep("", times=4))
row.names(d1)<-1:nrow(d1)
tt<-daply(d,.(IncomeType, Product), summarize, sum(Amount),.drop_i = F)
tt<-tt[-1,]
rrr<-rowSums(apply(tt,2, as.numeric))
tt<-cbind(tt,Total=rrr)
cc<-colSums(apply(tt, 2, as.numeric))
tt<-rbind(tt,Total=cc)
tt1<-daply(d,.(IncomeType, MaturityType), summarize, sum(Amount),.drop_i = F)
tt1<-tt1[-1,]
rrr<-rowSums(apply(tt1,2, as.numeric))
tt1<-cbind(tt1,Total=rrr)
cc<-colSums(apply(tt1, 2, as.numeric))
tt1<-rbind(tt1,Total=cc)
ECRR<-as.numeric(gsub(",","",e2[[2]][2,2]))-as.numeric(gsub(",","",e2[[2]][1,2]))
if(ECRR<0){
ECRR<-0
} else {ECRR=ECRR}
ECRR<-data.frame(ECRR)
names(ECRR)<-"OMG"
list(ECRR=ECRR,tt=tt,tt1=tt1,d1=d1)}
})
output$fileUploaded <- reactive({
return(!is.null(fund()))
})
outputOptions(output, 'fileUploaded', suspendWhenHidden=FALSE)
name<-c("ECRR","tt","tt1","details")
save.xlsx <- function (file, ...)
{
require(xlsx, quietly = TRUE)
objects <- list(...)
fargs <- as.list(match.call(expand.dots = TRUE))
objnames <- as.character(fargs)[-c(1, 2)]
nobjects <- length(objects)
for (i in 1:nobjects) {
if (i == 1)
write.xlsx(objects[[i]], file, sheetName = name[i])
else write.xlsx(objects[[i]], file, sheetName = name[i],
append = TRUE)
}
print(paste("Workbook", file, "has", nobjects, "worksheets."))
}
output$F<-renderTable({fund()$ECRR})
output$G<-renderTable({fund()$tt},rownames=T)
output$H<-renderTable({fund()$tt1},rownames=T)
output$I<-renderTable({fund()$d1},rownames=T)
output$downloadData <- downloadHandler(
filename = "ALM.xlsx",
content = function(file) {
save.xlsx(file,fund()$ECRR,fund()$tt,fund()$tt1,fund()$d1)
}
)
})
And ui.R
library(shiny)
shinyUI(pageWithSidebar (
headerPanel( "Fund"),
sidebarPanel(width=3,
fileInput('file1', 'Choose a file to upload',
accept = c(
'.pdf'
)),
helpText("(Only .pdf files can be uploaded"),
conditionalPanel("output.fileUploaded",
downloadButton('downloadData'))
),
mainPanel (
tabsetPanel(
tabPanel("ECRR", tableOutput("F")),
tabPanel("Product wise Distribution", tableOutput("G")),
tabPanel("Maturity wise Distribution", tableOutput("H")),
tabPanel("Details", tableOutput("I"))
))
)
)
If anybody wants to test the files I am trying to upload here are 2 of them
[File1][1]
[File2][2]
Sorry for the very messy code and thanks in advance.