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()
}
#####################################
Thanks in advance for any help you can offer. I am trying to create a GUI that allows the user to choose choose which directory the files are located then input some other information. I then want to be able to calculate information like how many files are in the folder, and some other information that is gained from the files. I need the values that the user inputs to do any of the analysis. However, when I use svalue() I get an error. I also want to summarize the information on a second tab of the notebook. Here's my code so far:
library(gWidgets)
library(gWidgets2)
library(gWidgets2RGtk2)
library(gWidgetsRGtk2)
library(gWidgetstcltk)
library(gWidgets2tcltk)
library(pdftools)
require(gWidgets2RGtk2)
fileChoose <- function(action="print", text = "Select a file...",
type="open", ...) {
gfile(text=text, type=type, ..., action = action, handler =
function(h,...) {
do.call(h$action, list(h$file))
})
}
path <- fileChoose(action="setwd", type="selectdir", text="Select a
directory...")
files <- list.files(path, full.names = TRUE)
files_ex <- file_ext(files)
win <- gwindow("DataMate Project")
grp <- ggroup(horizontal = FALSE, container=win)
nb <- gnotebook(container = grp, expand=TRUE)
group1 <- ggroup(horizontal = FALSE, container=nb, label = "Input")
x <- c("SELECT CUSTOMER", "Eaton", "NG", "Spectris", "Other")
n <- length(files_ex)
lyt <- glayout(cont = frame)
glabel("File Path to Docs", container = group1)
p <- gedit(path, container=group1)
glabel("To your knowledge is this an ITAR quote?", container = group1)
itar <- gradio(c("Non-ITAR","ITAR"), container=group1)
glabel("Who is the customer? (Parent company)", container = group1)
cust <- gcombobox(x, container=group1)
glabel("How many RFQs / Assemblies?", container = group1)
val <- gspinbutton(from=1, to = 100, by =1, value=1,container=group1)
run <- gbutton("Run", container = group1, gmessage(svalue(val))
Maybe this will get you a start:
show_gui <- function(parent, path) {
files <- list.files(path, full.names = TRUE)
files_ex <- tools::file_ext(files)
nb <- gnotebook(container = parent, expand=TRUE)
group1 <- gframe(horizontal = FALSE, container=nb, label = "Input", expand=TRUE)
x <- c("SELECT CUSTOMER", "Eaton", "NG", "Spectris", "Other")
n <- length(files_ex)
glabel("File Path to Docs", container = group1)
p <- gedit(path, container=group1)
glabel("To your knowledge is this an ITAR quote?", container = group1)
itar <- gradio(c("Non-ITAR","ITAR"), container=group1)
glabel("Who is the customer? (Parent company)", container = group1)
cust <- gcombobox(x, container=group1)
glabel("How many RFQs / Assemblies?", container = group1)
val <- gspinbutton(from=1, to = 100, by =1, value=1,container=group1)
run <- gbutton("Run", container = group1, handler = function(h, ...) {
gmessage(svalue(val))
})
}
w <- gwindow("GUI")
parentgroup <- ggroup(cont=w)
g = ggroup(cont=parentgroup, horizontal=FALSE)
glabel("Choose a file to proceed", cont=g)
gfilebrowse(cont=g, type="selectdir", handler=function(h, ...) {
dname = svalue(h$obj)
if (dir.exists(dname)) {
delete(parentgroup, g)
show_gui(parentgroup, dname)
} else {
gmessage("That file does not exists")
}
})
You had several mistakes. I didn't do the rest for you, but in the button handler you would create the widgets in a new tab, and use svalue(nb) <- 2 to switch to that tab.
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)
I am writing a GUI with the gwidgets package in R. I am implementing a tool that will allow the user to select a number of variables from one list, and drag them to an empty list for collection. The inspiration is the gui from SPSS, see link:
spss drag and drop
I was planning do this with two gtables, i.e. first create one gtable with the list of variables, and an empty gtable to collect the selected variables. Below is my sample code:
portfolioBuilder <- function(h,...){
## globals
widgets <- list()
varNames <- c("var1","var2","var3","var4" )#with(.GlobalEnv, names(data))
#window
win <- gwindow("Test")
#groups
g <- ggroup(horizontal = FALSE, container = win, expand = TRUE)
gg <- ggroup(horizontal = FALSE, container = win, expand = TRUE)
#graphics container
ggraphics(container = gg)
#paned group
pg <- gpanedgroup(container = g, expand = TRUE)
nb <- gnotebook(container = pg)
## main group
qpg <- ggroup(horizontal = FALSE, container = nb, label = "portfolio")
parg <- ggroup(horizontal = FALSE, container = nb, label = "portfolio args")
## qplot group
tbl <- glayout(container = qpg)
#variable list
tbl[1,1,anchor = c(1,0)] <- "Variables"
tbl[2:10,2] <- (widgets[["table"]] <- gtable(varNames, multiple = TRUE, container = tbl, expand = TRUE))
tbl[3,3, anchor = c(1,0)] <- "y"
tbl[3,4] <- (widgets[["y"]] <- gedit("", container = tbl))
tbl[4,3, anchor = c(1,0)] <- "x"
tbl[4,4] <- (widgets[["x"]] <- gtable(c(""),container = tbl))
## make table visible and set tab
visible(tbl) <- TRUE
svalue(nb) <- 1
##################################end layout#################################
}
However my sample code spits out an error because of the empty gtable widget. Does anyone know how to accomplish this with gwidgets?
You'll want to work on the layout, but the key to this is addDropSource and addDropTarget:
options(guiToolkit="RGtk2")
library(gWidgets)
w <- gwindow(visible=FALSE)
g <- gpanedgroup(cont=w)
tbl <- gtable(names(mtcars), cont=g)
fl <- gframe("variables", horizontal=FALSE, cont=g)
dep <- gedit(initial.msg="Dependent variable", label="Dependent", cont=fl)
ind <- gedit(initial.msg="Independent variable(s)", label="Independent", cont=fl)
addDropSource(tbl, handler=function(h,...) svalue(h$obj))
addDropTarget(dep, handler=function(h,...) svalue(h$obj) <- h$dropdata)
addDropTarget(ind, handler=function(h,...) {
cur <- svalue(h$obj)
new <- ifelse(nchar(cur) > 0, paste(cur, h$dropdata, sep=", "), h$dropdata)
svalue(h$obj) <- new
})
visible(w) <- TRUE
Drag and drop support in gWidgets is really variable. Of the 6 possibilities for this to work in: gWidgetsRGtk2, gWidgets2RGtk2, gWidgetstcltk, gWidgets2tcltk, gWidgetsQt and gWidgets2Qt this code only worked in gWidgetsRGtk2.
require(tcltk)
ttMain <- tktoplevel()
tktitle(ttMain) <- "ttMain"
launchDialog <- function() {
ReturnVal <- modalDialog("First Gene", "Enter A Gene Name", "")
if (ReturnVal == "ID_CANCEL") return()
tkmessageBox(title = "Heatmap",
message = paste("Hello, ", ReturnVal, ".", sep = ""))
}
launchDlg.button <- tkbutton(ttMain, text = "Launch Dialog", command = launchDialog)
tkpack(launchDlg.button)
I want to rewrite the last line of the code to have the message return a heatmap. I have a dataframe with all the data necessary (data about gene expression in numerical form), called pedM, and ReturnVal represents a column name (a particular gene) within that dataframe. Please help.
Any tips that can be provided would be amazing.
Thanks in advance.
Here is an example that may help. Your code uses a modalDialog function that AFAIK does not exist. Here is an example of how to roll your own
library(tcltk)
library(tcltk2)
tkinput <- function(parent, title, label, okButLabel="Ok", posx=NULL, posy=NULL) {
if(!require(tcltk2)) stop("This function requires the package tcltk2.")
if(!require(tcltk)) stop("This function requires the package tcltk.")
# param checks
if(!is.character(title)) stop("invalid title argument - character required.")
if(!is.character(label)) stop("invalid label argument - character required.")
# toplevel
tclServiceMode(FALSE) # don't display until complete
win <- tktoplevel(parent)
#win <- .Tk.subwin(parent)
tkwm.title(win, title)
tkwm.resizable(win, 0,0)
#tkconfigure(win, width=width, height=height)
# commands
okCommand <- function() if(!tclvalue(bookmVar)=="") tkdestroy(win) else tkfocus(te)
cancelCommand <- function () {
tclvalue(bookmVar) <- ""
tkdestroy(win)
}
tkwm.protocol(win, "WM_DELETE_WINDOW", cancelCommand)
# pack
f <- tk2frame(win)
w <- tk2label(f, text=label, justify="right")
tkpack(w, side="left", padx=5)
bookmVar <- tclVar("")
te <- tk2entry(f, textvariable=bookmVar, width=40)
tkpack(te, side="left", padx=5, fill="x", expand=1)
tkpack(f, pady=5)
f <- tk2frame(win)
w <- tk2button(f, text=okButLabel, command=okCommand)
tkpack(w, side="left", padx=5)
w <- tk2button(f, text="Cancel", command=cancelCommand)
tkpack(w, side="left", padx=5)
tkpack(f, pady=5)
# position
if(is.null(posx)) posx <- as.integer((as.integer(tkwinfo("screenwidth", win)) - as.integer(tkwinfo("width", win))) / 2.)
if(is.null(posy)) posy <- as.integer((as.integer(tkwinfo("screenheight", win)) - as.integer(tkwinfo("height", win))) / 2.)
geom <- sprintf("+%d+%d", posx, posy)
#print(geom)
tkwm.geometry(win, geom)
# run
tclServiceMode(TRUE)
ico <- tk2ico.load(file.path(R.home(), "bin", "R.exe"), res = "R")
tk2ico.set(win, ico)
tk2ico.destroy(ico)
tkfocus(te)
tkbind(win, "<Return>", okCommand)
tkbind(win, "<Escape>", cancelCommand)
tkwait.window(win)
tkfocus(parent)
return(tclvalue(bookmVar))
}
To plot an heatmap instead of a messagebox, you can use the tkrplot function
library(tkrplot)
heat_example <- function() {
x <- as.matrix(mtcars)
rc <- rainbow(nrow(x), start=0, end=.3)
cc <- rainbow(ncol(x), start=0, end=.3)
hv <- heatmap(x, col = cm.colors(256), scale="column",
RowSideColors = rc, ColSideColors = cc, margins=c(5,10),
xlab = "specification variables", ylab= "Car Models",
main = "heatmap(<Mtcars data>, ..., scale = \"column\")")
}
launchDialog <- function() {
ReturnVal <- tkinput(parent=ttMain, title="First Gene", label="Enter A Gene Name")
if (ReturnVal == "") return()
hmwin <- tktoplevel(ttMain)
img <- tkrplot(hmwin, heat_example)
tkpack(img, hmwin)
}
ttMain <- tktoplevel()
tktitle(ttMain) <- "ttMain"
launchDlg.button <- tkbutton(ttMain, text = "Launch Dialog", command = launchDialog)
tkpack(launchDlg.button, ttMain)
This code produces a heatmap, but gives also an error message I cannot resolve. Maybe someone else here can find the problem.