R code help- script does not work, but console works - r

Hi I am trying to run a r script
loadData <- function()
{
library(XLConnect)
excel0157 <- loadWorkbook("C:\\Users\\\\Documents\\R\\data\\0157\\0157.xlsx")
sheet_names <- getSheets(excel0157)
c0157 <- readWorksheetFromFile("C:\\Users\\\\Documents\\R\\data\\0157\\0157.xlsx",sheet = sheet_names[1],region = "B4:B27", header = FALSE)
for (i in 1:79) {
c0157[i] <-readWorksheetFromFile("C:\\Users\\\\Documents\\R\\data\\0157\\0157.xlsx",sheet = sheet_names[i],region = "B4:B27", header = FALSE)
}
c0157ts1 <- as.numeric(c(t(c0157)))
}
However, c0157ts1 does not create. If I run the c0157ts1 <- as.numeric(c(t(c0157))) in the console, c0157ts1 is created.
Can anyone explain why?

Related

Function with openxlsx works on R console but fails in Shiny

I'm trying to write a function to wrap up some data frames for export to Excel using the openxlsx package. It fails when running from a downloadHandler function in a Shiny app, but runs fine on the console in R.
Regular R script that runs fine:
library(openxlsx)
datDf1 <- data.frame(grr = c(1:10),
hrm = c(11:20),
boo = c(21:30))
datDf2 <- data.frame(will = c(31:40),
this = c(41:50),
work = c(51:60))
addSheetFun <- function(df, datName){
addWorksheet(wbExp, sheetName=datName)
writeData(wbExp, sheet=datName, df)
freezePane(wbExp, sheet=datName, firstRow=TRUE)
setColWidths(wbExp, sheet=datName, widths="auto", cols=1:ncol(df))
}
wbExp <- createWorkbook()
addSheetFun(datDf1, "SheetOne")
addSheetFun(datDf2, "SheetTwo")
Shiny application fails:
ui.r
shinyUI(
fluidPage(
downloadButton("xlExl", "Click to Export")
)
)
server.r
library(openxlsx)
library(shiny)
shinyServer(
function(
input, output, session
){
addSheetFun <- function(df, datName){
addWorksheet(wbExp, sheetName=datName)
writeData(wbExp, sheet=datName, df)
freezePane(wbExp, sheet=datName, firstRow=TRUE)
setColWidths(wbExp, sheet=datName, widths="auto", cols=1:ncol(df))
}
output$xlExl <- downloadHandler(
filename="Test.xlsx",
content=function(file){
datDf1 <- data.frame(grr = c(1:10),
hrm = c(11:20),
boo = c(21:30))
datDf2 <- data.frame(will = c(31:40),
this = c(41:50),
work = c(51:60))
wbExp <- createWorkbook()
addSheetFun(datDf1, "SheetOne")
addSheetFun(datDf2, "SheetTwo")
saveWorkbook(wbExp, file, overwrite=TRUE)
}
)
}
)
The error I get when running from Shiny is: "Warning: Error in %in%: object 'wbExp' not found
[No stack trace available]"
I played around with tacking this this to the top of addSheetFun:
if (exists("wbExp")) {
wbExp <- wbExp
}
else {
wbExp <- createWorkbook()
}
and then calling it like so:
wbExp <- addSheetFun(datDf1, "SheetOne")
wbExp <- addSheetFun(datDf2, "SheetTwo")
but that only manages to overwrite the first sheet with the second.
Thoughts?
The Error explains why it fails, it can't find your wbExp.
Probably the easiest way to overcome the error is by using <<- when you createWorkbook.
So wbExp <<- createWorkbook(). Then your shiny app should work.
This is like 'superassignment' and will assign the object in the parent environment (suggest reading http://adv-r.had.co.nz/Environments.html)
Alternatively, you can include addSheetFun inside the downloadHandler just before
wbExp <- createWorkbook().
So server.R
library(openxlsx)
library(shiny)
shinyServer(
function(
input, output, session
){
output$xlExl <- downloadHandler(
filename="Test.xlsx",
content=function(file){
datDf1 <- data.frame(grr = c(1:10),
hrm = c(11:20),
boo = c(21:30))
datDf2 <- data.frame(will = c(31:40),
this = c(41:50),
work = c(51:60))
addSheetFun <- function(df, datName){
addWorksheet(wbExp, sheetName=datName)
writeData(wbExp, sheet=datName, df)
freezePane(wbExp, sheet=datName, firstRow=TRUE)
setColWidths(wbExp, sheet=datName, widths="auto", cols=1:ncol(df))
}
wbExp <- createWorkbook()
addSheetFun(datDf1, "SheetOne")
addSheetFun(datDf2, "SheetTwo")
saveWorkbook(wbExp, file, overwrite=TRUE)
}
)
}
)

Function that imports data

Im trying to create a function that imports my data into R. Whenever I call this function though it runs through it but I don't see my data set anywhere
inputData <- function(){
teams <- read.csv('C:/Users/BT_1N3_24/Desktop/PremierLeaguePlayers.csv', header = TRUE)
currentTeam <- read.csv('C:/Users/BT_1N3_24/Desktop/TeamStats.csv', header = TRUE)
}
All functions are locally scoped in R. If you want to pass something out of the environment, it must be returned as an object. I would write your code like this:
inputData <- function(){
teams <- read.csv('C:/Users/BT_1N3_24/Desktop/PremierLeaguePlayers.csv', header = TRUE)
currentTeam <- read.csv('C:/Users/BT_1N3_24/Desktop/TeamStats.csv', header = TRUE)
list(teams, currentTeam)
}
## call the function
data.list <- inputData()

Read csv using gfilebrowse from gWidgets

I am trying to build a GUI using gWidgets R library to download satellite imagery. The intention is to read the urls from a comma separated values file. The GUI looks ok but it does not do what I expect it to do. I am doing something wrong, any help is greatly appreciated.
Here is the sample data:
Online.Access.URLs <- c("http://e4ftl01.cr.usgs.gov//MODIS_Composites/MOLT/MOD09A1.005/2000.02.18/MOD09A1.A2000049.h09v06.005.2006268183648.hdf",
"http://e4ftl01.cr.usgs.gov//MODIS_Composites/MOLT/MOD09A1.005/2000.02.26/MOD09A1.A2000057.h09v06.005.2006270065224.hdf",
"http://e4ftl01.cr.usgs.gov//MODIS_Composites/MOLT/MOD09A1.005/2000.03.05/MOD09A1.A2000065.h09v06.005.2006269234536.hdf")
Producer.Granule.ID <- c("MOD09A1.A2000049.h09v06.005.2006268183648.hdf",
"MOD09A1.A2000057.h09v06.005.2006270065224.hdf",
"MOD09A1.A2000065.h09v06.005.2006269234536.hdf")
df <- data.frame(Producer.Granule.ID,Online.Access.URLs)
write.csv(df,"C:\\GUI_test\\h09v06v3.csv",row.names=FALSE)
And this is my try:
my.DownloadHDF <- function(){
library(gWidgets)
library(gWidgetstcltk)
library(RCurl)
options(guiToolkit = "tcltk")
win <- gwindow("Download HDF with R!", visible = FALSE)
csv.frame <- gframe("csv file ", container = win)
csv.label <- glabel("csv with HDF's names ", container = csv.frame)
csv.file.name <- gfilebrowse("Select csv file", type="open",cont=csv.frame,action="read.csv")
dir.frame <- gframe("Output Directory ", container = win)
dir.label <- glabel("Where to save HDF's? ", container = dir.frame)
dir.out <- gfilebrowse("Select folder ",type = "selectdir", cont=dir.frame)
dlw.frame <- gframe("Download ", container = win)
dlw.label <- glabel(" ", container = dlw.frame)
btnDwn <- gbutton("Start Download", container = dlw.frame,
handler = function(csv.file.name,dir.out){
df <- read.csv(csv.file.name, header=TRUE,sep=",")
hdf.urls <- df$Online.Access.URLs
hdf.urls <- as.character(hdf.urls)
hdf.names <- df$Producer.Granule.ID
hdf.names <- as.character(hdf.names)
for (i in 1:length(hdf.names)){
URL <- hdf.urls [i]
file <- hdf.names[i]
download.file(URL,paste(dir.out,file,sep=""),mode="wb")
cat(paste("Composite number ",i,"successfully downloaded!"),sep="\n")
cat("\n\n\n\n\n\n\n\n")
}})
visible(win) <- TRUE
}
my.DownloadHDF()
I am using R-3.2.2 with RStudio 0.98.1103.
Here is the script after the improvements. Now it does exactly what I expect it to do. I hope someone finds it useful:
# load functions ####
# download function
f.d <- function(hdf.urls,hdf.names,out.dir){
for(i in 1:length(hdf.urls)){
URL <- hdf.urls [i]
file <- hdf.names [i]
download.file(URL,paste(out.dir,"/",file,sep=""),mode="wb")
}}
# read csv function
f.csv <- function(x){
df1 <<- read.csv(x,header=TRUE,sep=",")
hdf.urls <<- df1$Online.Access.URLs
hdf.urls <<- as.character(hdf.urls)
hdf.names <<- df1$Producer.Granule.ID
hdf.names <<- as.character(hdf.names)
}
# load functions ####
# my.DownloadHDFv2 this one works fine ####
my.DownloadHDF <- function(){
options(guiToolkit = "tcltk")
win <- gwindow("Download HDF with R!", visible = FALSE)
csv.frame <- gframe("csv with HDFs names ", container = win)
a <- gfilebrowse("Upload csv file",cont=csv.frame,
handler=function(h,...){
f.csv(svalue(a))
})
path.frame <- gframe("Output Directory ", container = win)
brow <- gfilebrowse(text = "Select folder...", type = "selectdir",container=path.frame,
handler=function(h,...){
out.dir <<- svalue(brow)
})
b <- gbutton(text="Start Download",container = win,
handler = function(h,...){
f.d(hdf.urls,hdf.names,out.dir=out.dir)
})
visible(win)<-TRUE
}
my.DownloadHDF()
# my.DownloadHDFv2 this one works fine ####

tcltk R - how to access value returned by function

I just started with tcltk and R. And I am having troubles accessing a computed value by a function called myFun1 when calling a second function myFun2:
Here is a simplified version of my UI:
Simple tcltk interface
library(tcltk)
tt <- tktoplevel()
topMenu <- tkmenu(tt)
tkconfigure(tt, menu = topMenu)
fileMenu <- tkmenu(topMenu, tearoff = FALSE)
tkadd(fileMenu, "command", label = "Function1", command = myFun1)
tkadd(fileMenu, "command", label = "Function2", command = myFun2)
tkadd(topMenu, "cascade", label = "Tab", menu = fileMenu)
tkfocus(tt)
My functions
myFun1 <- function() {
compVal <- 2*3
compVal
}
myFun2 <- function() {
msg <- paste("The value is: \n", compVal )
mbval<- tkmessageBox(title="This is the title",
message=msg,type="yesno",icon="question")
}
Calling myFun1 works, but myFun2 returns
Error in paste("The value is: \n", compVal) :
Object 'compVal' not found
Also wrapping compVal into return(compVal) doesn`t work.
I was also thinking of doing:
res <- list(compVal=compVal)
but I am not able to access the created list with myFun2.
Any sugesstions on how to access the returned value form myFun1 inside myFun2?
I found a solution, at first I thought its not really a "clean" way of doing it, but even in the offical documentation it is done this way.
Simply create a global variable using <<- :
myFun1 <- function() {
compVal <<- 2*3
}

Building GUI with Tcltk

I'm very new in R and I'm trying to build a GUI using Tcltk package. I'm not sure how the "tkGetOpenFile" works. I thought by using this function it would open and hold my dataset into the workspace of the RStudio. But the only thing that happens is a popup window to choose the file.
The code I'm using is below.
Please help me!!!
require(tcltk)
readCsv <- function(){
myval <- tkgetOpenFile()
mydata <- read.csv(paste(as.character(myval), collapse = " "))
assign("myData", mydata, envir = .GlobalEnv)
}
tt <- tktoplevel()
topMenu <- tkmenu(tt)
tkconfigure(tt, menu = topMenu)
fileMenu <- tkmenu(topMenu, tearoff = FALSE)
tkadd(fileMenu, "command", label = "Quit", command = function() tkdestroy(tt))
tkadd(fileMenu, "command", label = "Load", command = function() readCsv())
tkadd(topMenu, "cascade", label = "File", menu = fileMenu)
tkfocus(tt)
You need to use the tclvalue function to get an R character string representation of a Tcl variable. Modify your function as follows:
readCsv <- function(){
myval <- tclvalue(tkgetOpenFile()) # add `tclvalue` here
mydata <- read.csv(myval) # then `myval` is a character string
assign("myData", mydata, envir = .GlobalEnv)
}

Resources