I am trying to load the .rdata object through user input , if the object is found then get the length of the list that is stored in the object else length is 1.
I am using the below code:
output$M_name<-renderUI({
if(file.exists(obj_name())==TRUE)
{
modname<<-load(file=objname,envir=sys.frame())
ver<<- length(get(modname))+1
str1 <- paste0("- ",isolate(input$model_name)," already EXISTS.")
str2 <- paste("- Please upload the new data csv file of the above mentioned model")
HTML(paste(str1, str2, sep = "<br/>"))
}else
{
modname<<-isolate({input$model_name})
ver<<-length(get(modname))+1
str1<-paste0("- ",isolate(input$model_name)," does not EXIST")
str2<-paste("- Please use the same name, if you have already uploaded base model details before")
str3<-paste("- If this is the first time, Please upload the csv file on the next page")
HTML(paste(str1, str2, str3, sep = "<br/>"))
}
})
The file gets loaded and the object is saved in "modname" but i do not see the "ver" variable in the r environment.
I am fairly new to R shiny, please bear with my coding.
Related
I've created this function to open a file in R:
openfasta<-function(DNAseq){
DNASeq <- readline(prompt = "Enter the .fasta file name:")
readLines(DNASeq)
Now if the file can not be found in the working directory, the script must output a
warning message and ask for the file name repetitively until the file is located.
I tried this, but it didn't work:
if (DNASeq) {
return()
}
else {
cat(DNASeq <- readline(prompt = "Enter the .fasta file name:"))
}
}
I think if a For loop would be a reasonable solution too.
You can use a while loop to check for file existence. If not found use a print statement to display a warning and prompt again.
openfasta <- function(DNAseq){
while(!file.exists(DNAseq)){
print("The file you requested was not found.")
DNASeq <- readline(prompt = "Enter the .fasta file name:")
}
readLines(DNASeq)
}
I'm want to save my program logging in a text file using R. I was able to save my entire logging in the text file. However, the challenge is text file name should have date and time. for example:
file1<- function(x){
flog.info("hi",name = 'trail')
summary = summary(x)
mean = mean(x,na.rm=T)
outpurt = list(summary,mean)
return(outpurt)
}
calling this function
files = file1(airquality)
since, i need to add date and time
Curr_date = (Sys.time()
appender function is used, in order to save the logging(file.info mentioned above).
flog.appender(appender.file(sprintf(paste0(Curr_date,'.log))),
name='trail.io')
you can see that, i was trying to use paste0 function in order to get the text file name with date and time. nothing works
filename = paste(gsub(":", "-", Sys.time()),"_file.txt",sep="")
# [1] "2016-12-29 00-49-08_file.txt"
# to write the content to a .txt file with the above filename
write.table("your content", file = paste0("D:/", filename))
Did I understand the problem correctly?
x = as.character(as.POSIXct(Sys.time()))
filename = paste(x,"_file.csv",sep="")
filename = gsub(":","-",filename)
filename = gsub(" ","_",filename)
I was able to save the file with date and time. The appender function. flog.appender() should be used first and then we should use flog.info() inside every function.
result<- function(x1,y){
require(futile.logger)#package name
x= Sys.time()
flog.appender(paste(x1,y,format(x,%y-%m-%d %I %p"),".log",sep ="")) #save file with date and time. for futile.logger see r bloggers.
}
I'm new to R (and programming in general), so apologies if this has been answered elsewhere. I was not able to find an answer via searching, but any help or direction would be great!
I'm trying to make a clickable interface in R, where I can have users click to find a file of choice that proceeds to get automatically analyzed in R.
Here's what I'm having trouble with:
require(tcltk)
getfile <- function() {name <- tclvalue(tkgetOpenFile(
filetypes = "{{CSV Files} {.csv}}"))
if (name == "") return;
datafile <- read.csv(name,header=T)
}
tt <- tktoplevel()
button.widget <- tkbutton(tt, text = "Select CSV File to be analyzed", command = getfile)
tkpack(button.widget)
# The content of the CSV file is placed in the variable 'datafile'
Yet when I try to execute it, and click on a CSV file of interest after the button pops up, nothing happens. By that I mean R gives me the error below when I type in datafile.
Error: object 'datafile' not found
Once again, any help is much appreciated. Thanks!
The top level object has an environment in which you can store things, keeping them local to the GUI. Give your callbacks that object as an argument:
# callback that reads a file and stores the DF in the env of the toplevel:
getfile <- function(tt) {name <- tclvalue(tkgetOpenFile(
filetypes = "{{CSV Files} {.csv}}"))
if (name == "") return;
tt$env$datafile <- read.csv(name,header=T)
}
# callback that does something to the data frame (should check for existence first!)
dosomething <- function(tt){
print(summary(tt$env$datafile))
}
# make a dialog with a load button and a do something button:
tt <- tktoplevel()
button.choose <- tkbutton(tt, text = "Select CSV File to be analyzed", command = function(){getfile(tt)})
tkpack(button.choose)
button.dosomething <- tkbutton(tt, text = "Do something", command = function(){dosomething(tt)})
tkpack(button.dosomething)
That should be fairly robust, although I'm not sure if there's anything already in the environment that you should beware stomping on, in which case create an environment in that environment and use that for your local storage.
If you want to quit the dialog and save things for the user, prompt for a name and use assign to store them in .GlobalEnv on exit.
This is in continuation of my related question: Error when trying to interactively load data file saved by paused batch script. I decided to present my question with a reproducible example separately to avoid making the already large description in the previous question even bigger. In the following reproducible example, I expect to retrieve the value of the stored object ("Important data"), but instead, as you see, I retrieve the name of the object itself ("sf.data.devLinks"). I suspected that it could be because of me using as.name, but I tested additionally a primitive example in an interactive session and as.name worked fine. I also, as you see, have tried using eval and substitute, but it didn't help.
library(RCurl)
info <- "Important data"
ATTR <- "SQL"
request <- "SELECT info FROM topSecret"
dataName <- "sf.data.devLinks"
rdataFile <- "/tmp/testAttr.rds"
save <- TRUE
getData <- function() {
return (info)
}
requestDigest <- base64(request)
# check if the archive file has already been processed
message("\nProcessing request \"", request, "\" ...\n")
# read back the object with the attribute
if (file.exists(rdataFile)) {
# now check if request's SQL query hasn't been modified
data <- readRDS(rdataFile)
message("Retrieved object '", data, "', containing:\n")
message(str(data))
requestAttrib <- attr(data, ATTR, exact = TRUE)
if (is.null(requestAttrib)) {
message("Object '", data, "' doesn't have attribute \"",
ATTR, "\"\n")
}
else {
message("Object '", data, "' contains attribute ", ATTR, ":\n\"",
base64(requestAttrib), "\"\n")
if (identical(requestDigest, requestAttrib)) {
message("Processing skipped: RDS file is up-to-date.\n")
save <- FALSE
return
}
}
rm(data)
}
if (save) {
message("Saving results of request \"",
request, "\" as R data object ...\n")
assign(dataName, getData())
data <- as.name(dataName)
#eval(substitute(assign(dataName, getData()),
# list(data <- as.name(dataName))))
# save hash of the request's SQL query as data object's attribute,
# so that we can detect when configuration contains modified query
attr(data, ATTR) <- base64(request)
# save current data frame to RDS file
saveRDS(data, rdataFile)
}
Please note that testing this code requires running it twice (first run - to store the object, second - to retrieve).
The problem is in your use of as.name, not in the code to save the object. This works perfectly fine:
data <- 1:10
object.name <- 'data.name'
query <- 'SELECT * FROM TABLE'
file <- tempfile()
assign(object.name, structure(data, SQL = query))
saveRDS(get(object.name), file)
read.object <- readRDS(file)
identical(read.object, get(object.name))
You're creating a name object, and assigning attributes to it, but you're expecting the data to be there. It won't be, a symbol is just a pointer to the value. You need to use eval() or something similar to get the value from the symbol.
Finally, I was able to return to this question. I have figured out the correct solution, so I'm answering my own question. The answer here is based on my reproducible example, but I have made corresponding changes in my more complex real-world R code. The solution is rather simple, but twofold, as follows.
Replace the original code data <- readRDS(rdataFile) with assign(dataName, readRDS(rdataFile)).
Replace the original code as.name(dataName) with get(dataName). An alternative to get() here is eval(parse(text=dataName)), which IMHO is more cumbersome.
Below I provide the solution's full source code, based on the original reproducible example. I don't provide the script's output, which is easy to reproduce (remember to run script at least twice). Again, thanks to everyone who helped with this question.
library(RCurl)
info <- "Important data"
ATTR <- "SQL"
request <- "SELECT info FROM topSecret"
dataName <- "sf.data.devLinks"
rdataFile <- "/tmp/testAttr.rds"
save <- TRUE
getData <- function() {
return (info)
}
requestDigest <- base64(request)
# check if the archive file has already been processed
message("\nProcessing request \"", request, "\" ...\n")
# read back the object with the attribute
if (file.exists(rdataFile)) {
# now check if request's SQL query hasn't been modified
assign(dataName, readRDS(rdataFile))
message("Retrieved object '", dataName, "', containing:\n")
message(str(get(dataName)))
requestAttrib <- attr(get(dataName), ATTR, exact = TRUE)
if (is.null(requestAttrib)) {
message("Object '", dataName, "' doesn't have attribute \"",
ATTR, "\"\n")
}
else {
message("Object '", dataName, "' contains attribute \"",
ATTR, "\":\n\"", base64(requestAttrib), "\"\n")
if (identical(requestDigest, requestAttrib)) {
message("Processing skipped: RDS file is up-to-date.\n")
save <- FALSE
return
}
}
}
if (save) {
message("Saving results of request \"",
request, "\" as R data object ...\n")
assign(dataName, getData())
message(str(dataName))
data <- get(dataName)
# alternative to using get(), but more cumbersome:
# data <- eval(parse(text=dataName))
# save hash of the request's SQL query as data object's attribute,
# so that we can detect when configuration contains modified query
attr(data, ATTR) <- base64(request)
message(str(data))
# save current data frame to RDS file
saveRDS(data, rdataFile)
}
I have a data frame called, Fail.
I would like to save Fail as a CSV in a location that the user selects. Below is some example code that I found, but I don't know how to incorporate Fail into it.
require(tcltk)
fileName <- tclvalue(tkgetSaveFile())
if (!nchar(fileName)) {
tkmessageBox(message = "No file was selected!")
} else {
tkmessageBox(message = paste("The file selected was", fileName))
}
Take a look at the write.csv or the write.table functions. You just have to supply the file name the user selects to the file parameter, and the dataframe to the x parameter:
write.csv(x=df, file="myFileName")
You need not to use even the package "tcltk". You can simply do as shown below:
write.csv(x, file = "c:\\myname\\yourfile.csv", row.names = FALSE)
Give your path inspite of "c:\myname\yourfile.csv".
write.csv([enter name of dataframe here],file = file.choose(new = T))
After running above script this window will open :
Type the new file name with extension in the File name field and click Open, it'll ask you to create a new file to which you should select Yes and the file will be created and saved in the desired location.