LOGGER IN r, msg function in R - r

I am a beginner in R,
While I have to edit some pre written codes in R.
there is a specific one which I cannot understand.
it would be really helpful if anyone can help me understand this.
# Logger
log.msg = function(msg){
## capture messages and errors to a file.
fileConn<-file("output.txt", open = "a+")
writeLines(c(msg), fileConn)
close(fileConn)
}
log.msg("Start Data extraction and merging..")

log.msg = function(msg){
## capture messages and errors to a file.
## create file connection in append mode (a+)
fileConn<-file("output.txt", open = "a+")
## write the msg to this file
writeLines(c(msg), fileConn)
## close connection
close(fileConn)
}

Related

Automatically sink() when exiting function when there is a error

I want to write a error log for one of my functions (see below). However, when the function fails, the sink won't get closed properly. Is there a way to always close the sinks() upon exiting the function?
some_function <- function(){
con <- file("test.log")
sink(con, append=TRUE,type="output",split=TRUE)
sink(con, append=TRUE,type="message")
>> do some stuff that may fail.
sink()
sink(type = "message")
}
Use try.
try(lm(1), outFile="error.txt") ## failing stuff
File contains:
Error in formula.default(object, env = baseenv()) : invalid formula

R - capture output from system() to a txt file.

I want to capture all output from R console. I tried to use sink() function and txtStart() of library 'TeachingDemos'. However, none of them can capture the output from system() command.
For example
If I run the below codes:
zz <- file("log.txt")
sink(zz)
sink(zz, type = "message")
print('first layer message!!!!')
system("Rscript test1.R") #test1.R is a R script that print 'hello world'
sink(type = "message")
sink()
I can see the message 'hello world' in the R console. However, I cannot write it into log.txt. Is there any way to solve this?
Thanks
system("Rscript test1.R", intern = TRUE)

is reading .wma sound files in R possible?

Is the there a way to read .WMA sound files in R or the copyright restrictions do not allow this?
The final aim is to convert it to another format (MP3/WAV)
In one or another way R audio packages use ffmpeg converter.
Please see the following options:
After its download you can use R to convert WMA to MP3 file format
directly by system function call;
or you can use ffmpeg wrapper package for simple audio conversions. However it is Linux-oriented it could be easily transformed into Windows compatible one.
Please see the code below for Option 2:
# install.packages("devtools")
# library(devtools)
# install_github("pmur002/ffmpeg")
library(ffmpeg)
# set path to your ffmpeg.exe file
ffmpeg_path <- "C:\\<Path to ffmpeg>\\ffmpeg-20180906-70a7087-win64-static\\bin\\ffmpeg.exe"
ffmpeg_win <- function (inputs, outputs, filters = NULL, overwrite = FALSE,
wait = TRUE, echo = FALSE) {
if (!is.null(filters)) {
stop("Filters are currently unsupported")
}
if (inherits(inputs, "FFmpeg_input")) {
inputs <- list(inputs)
}
if (inherits(outputs, "FFmpeg_output")) {
outputs <- list(outputs)
}
options <- ""
if (overwrite) {
options <- paste0(options, "-y ")
}
cmd <- paste(ffmpeg_path, options, do.call(paste, inputs), do.call(paste,
outputs))
system(cmd, wait = wait)
if (echo) {
cat(cmd, "\n")
}
}
# just copy to your working directory required file, here is for example "mellow.wma"
ffmpeg_win(fileInput("mellow.wma"), fileOutput("mellow.mp3"), echo = TRUE)

Download files from FTP folder using Loop

I am trying to download all the files inside FTP folder
temp <- tempfile()
destination <- "D:/test"
url <- "ftp://XX.XX.net/"
userpwd <- "USER:Password"
filenames <- getURL(url, userpwd = userpwd,ftp.use.epsv = FALSE,dirlistonly = TRUE)
filenames <- strsplit(filenames, "\r*\n")[[1]]
When I am printing "filenames" I am getting all the file names which are inside the FTP folder - correct output till here
[1] "2018-08-28-00.gz" "2018-08-28-01.gz"
[3] "2018-08-28-02.gz" "2018-08-28-03.gz"
[5] "2018-08-28-04.gz" "2018-08-28-05.gz"
[7] "2018-08-28-08.gz" "2018-08-28-09.gz"
[9] "2018-08-28-10.gz" "2018-08-28-11.gz"
[11] "2018-08-28-12.gz" "2018-08-28-13.gz"
[13] "2018-08-28-14.gz" "2018-08-28-15.gz"
[15] "2018-08-28-16.gz" "2018-08-28-17.gz"
[17] "2018-08-28-18.gz" "2018-08-28-23.gz"
for ( i in filenames ) {
download.file(paste0(url,i), paste0(destination,i), mode="w")
}
I got this error
trying URL 'ftp://XXX.net/2018-08-28-00.gz'
Error in download.file(paste0(url, i), paste0(destination, i), mode = "w") :
cannot open URL 'ftp://XXX.net/2018-08-28-00.gz'
In addition: Warning message:
In download.file(paste0(url, i), paste0(destination, i), mode = "w") :
InternetOpenUrl failed: 'The login request was denied'
I modified the code to
for ( i in filenames )
{
#download.file(paste0(url,i), paste0(destination,i), mode="w")
download.file(getURL(paste(url,filenames[i],sep=""), userpwd =
"USER:PASSWORD"), paste0(destination,i), mode="w")
}
After that, I got this error
Error in function (type, msg, asError = TRUE) : RETR response: 550
Without a minimal, complete, and verifiable example it is a challenge to directly replicate your problem. Assuming the file names don't include the URL, you'll need to combine them to access the files.
download.file() requires a file to be read, an output file, as well as additional flags regarding whether you want a binary download or not.
For example, I have data from Alberto Barradas' Pokémon Stats kaggle.com data set stored on my Github site. To download some of the files to the test subdirectory of my R Working Directory, I can use the following code:
filenames <- c("gen01.csv","gen02.csv","gen03.csv")
fileLocation <- "https://raw.githubusercontent.com/lgreski/pokemonData/master/"
# use ./ for subdirectory of current directory, end with / to work with paste0()
destination <- "./test/"
# note that these are character files, so use mode="w"
for (i in filenames){
download.file(paste0(fileLocation,i),
paste0(destination,i),
mode="w")
}
...and the output:
The paste0() function concatenates text without spaces, which allows the code to generate a fully qualified path name for the url of each source file, as well as the subdirectory where the destination file will be stored.
To illustrate what's happening with paste0() in the for() loop, we can use message() to print to the R console.
> # illustrate what paste0() does
> for (i in filenames){
+ message(paste("Source is: ",paste0(fileLocation,i)))
+ message(paste("Destination is:",paste0(destination,i)))
+ }
Source is: https://raw.githubusercontent.com/lgreski/pokemonData/master/gen01.csv
Destination is: ./test/gen01.csv
Source is: https://raw.githubusercontent.com/lgreski/pokemonData/master/gen02.csv
Destination is: ./test/gen02.csv
Source is: https://raw.githubusercontent.com/lgreski/pokemonData/master/gen03.csv
Destination is: ./test/gen03.csv
>

R: Create a txt file with the error handling of tryCatch

I want to know if there is the possibility to create a log with the information of the "error" that force the tryCatch to do "error handling"?
Is to be able to gain visibility of potential errors. I want to avoid doing prints.
Thanks!
this will work:
outputFile <-file("output.txt")
tryCatch({
--- your code ---
}, error = function(e) {
writeLines(as.character(e), outputFile)
})
-----------------------------
close(outputFile)

Resources