Invoke a system command from R with dynamic variable name - r

I want to call python script using the system command. I am passing a parameter with it, but the variable is dynamic. I am not sure how to paste the filename dynamically. I would like the Filename to be changed depending on the user input.
system('python testMethod.py Filename', wait = TRUE)

Use paste0 to create the command string:
filenname <- "Filename"
system(paste0("python testMethod.py ", filename), wait = TRUE)
Edit:
M--'s suggestion does make it cleaner:
filenname <- "Filename"
system(paste("python testMethod.py", filename), wait = TRUE)

Related

Is there an R function to create a raw string based on an existing object?

I am creating a filepath to read in R through a hard coded raw string (because otherwise the filepath raises an error):
filepath <- r"(C:\User\me\folder\data)"
However, I would like to create the following functionality to prevent the user from writing directly the filepath within the raw string:
filepath <- "C:\User\me\folder\data"
# I know the as_raw function doesn't exist, but I am wondering whether there is something similar
filepath <- as_raw(filepath)
Is there any R function that does this? Or should the user always modify the raw string (or use a readline function)?
Any of these could be used:
filepath <- "C:/User/me/folder/data"
filepath <- "C:\\User\\me\\folder\\data"
filepath <- file.path("C:", "User", "me", "folder", "data")
filepath <- file.choose() # if file exists. Interactive.
filepath <- choose.dir() # same but for directory
filepath <- readClipboard() # if filepath is on clipboard. \ is ok.
filepath <- r"(C:\User\me\folder\data)"
You could either ask the user to submit a file path with two forward slashes:
filepath <- "C://User//me//folder//data"
Or you can just ask for the part after the user name and then glue it together with the user path:
folder <- "folder//data"
filepath <- paste0("C://Users//", Sys.info()["user"], "//", folder)
charToRaw(filepath)
Should do what you want, I think.

save the text file using date and time in r

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.
}

Data not appending with R when writing

I am writing output to a file but the data is not appending. It is creating the last row each time. The code is as follows
op <- function(crime) {
filename <- paste(crime,".txt")
fileconn <- file(filename)
cat(nthecrime, file=fileconn, sep=" ",append=TRUE)
#write(nthecrime,file=fileconn, ncolumns=9, append=TRUE,sep="\t")
close(fileconn)
}
Both cat & write create a new file each time I call the above lines instead of appending. What am I missing?
Regards
Ganesh
From the ?cat help:
append logical. Only used if the argument file is the name of file
(and not a connection or "|cmd"). If TRUE output will be appended to
file; otherwise, it will overwrite the contents of file.
You should use filename, not fileconn. Try
cat(nthecrime, file=filename, sep=" ",append=TRUE)

How to save a data frame as CSV to a user selected location using tcltk

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.

Interactively ask user for filename before saving file

I want to save the my tab delim files manually. I mean that I want user to choose the directory and file name when he wants to save the data. (For an example I have merged individual files into single file and want to save it.)
Usually I use write.table but in write.table we define the directory path and file name within that function but I want a function in which user can save file with any name in his desired directory.
Just use the file.choose() function,like this:
write.table(yerdata, file = file.choose(new = TRUE))
On Windows, at least, that will bring up a dialog for save-as commands.
Annoyingly the tcltk package doesn't have a function for 'Save As', it only has a file selector for choosing an existing file.
Luckily you can take the DIY approach via some tcl calls:
require(tcltk)
write.table(yerdata,file = tclvalue(tcl("tk_getSaveFile")))
The tk_choose.files function source could be used as a template to write a nicer interface to tcl("tk_getSaveFile") if needed. Does seem to be a glaring omission in package:tcltk though...
Using gWidgets:
gfile("Save yerdata", type = "save", handler = function(h, ...)
{
write.table(yerdata, file = h$file)
})
One (perhaps less than ideal) option would be to use readline to prompt the user for the full path and file name (or just the file name if you want to programmatically choose the directory) and then simply pass that value on the write.table. Here's a sketch:
FILE_PATH <- readline(prompt = "Enter a full path and file name: ")
#Some checking to make sure you got a valid file path...
write.table(yerdata, file = FILE_PATH)
Note that as per ?readline this will really only work when running R interactively.
As it is 2017 now, the tcltk2 package is an improvement of tcltk:
library(tcltk2)
filename <- tclvalue(tkgetSaveFile())
if (!nchar(filename)) {
tkmessageBox(message = "No file was selected!")
} else {
tkmessageBox(message = paste("The file selected was", filename))
}
And the use of filters, let's say one should only save as JPG/JPEG:
jpeg_filename <- tclvalue(
tkgetSaveFile(initialfile = "foo.jpg",
filetypes = "{ {JPEG Files} {.jpg .jpeg} } { {All Files} * }")
)

Resources