R Url function on Mac - r

When running the following call on Mac I get an error as follows
jsonlite::fromJSON(url(paste("https://fantasy.premierleague.com/api/element-summary/236")))
Error in parse_con(txt, bigint_as_char) : parse error: premature EOF
(right here) ------^
However the following call works correctly, with the only difference being the omission of the url().
jsonlite::fromJSON(paste("https://fantasy.premierleague.com/api/element-summary/236"))
The traceback from the error is as follows:
4: parse_con(txt, bigint_as_char)
3: parseJSON(txt, bigint_as_char)
2: parse_and_simplify(txt = txt, simplifyVector = simplifyVector,
simplifyDataFrame = simplifyDataFrame, simplifyMatrix = simplifyMatrix,
flatten = flatten, ...)
1: jsonlite::fromJSON(url(paste("https://fantasy.premierleague.com/api/element-summary/236")))
I've tried on two separate installations with the same result. I wonder if the line break after the first line of the JSON is being interpreted as EOF....

Related

Why can't i parse my R code in a Jupyter Notebook?

I tried to use R in a Jupyter Notebook with VSCode, but I get the following Error:
summary(mtcars)
ERROR: Error in parse(text = x, srcfile = src): <text>:1:16: unerwartete Eingabe
1: summary(mtcars)
^
Error in parse(text = x, srcfile = src): <text>:1:16: unerwartete Eingabe
1: summary(mtcars)
^
Traceback:
It seems like I there's a problem with the newline command, because I can execute multiple cells with one line of code each.
Changing the End of Line Command in VSCode from "\r\n" to "\n" did the trick...

Capture an uncapturable error

I want to capture an error from D%4 and move on. The error is:
Error: unexpected input in "D%4"
Typically if a function is being called the following works:
capture_warn_error <- function(x){
tryCatch({
x
}, warning = function(w) {
w
}, error = function(e) {
e
})
}
capture_warn_error(D%4)
But the no recovery is possible as `D%4 shuts down everything immediately:
## > capture_warn_error(D%4)
## Error: unexpected input in "capture_warn_error(D%4)"
Is there anyway to capture such a stubborn beast and move on? I know D%4 isn't an object but this works for other non objects:
capture_warn_error(means)
## <simpleError in doTryCatch(return(expr), name, parentenv, handler): object 'means' not found>
It's be nice to:
Understand why D%4 is unrecoverable vs means
Find a way to recover still and capture D%4's error
As others have stated it is because text typed at the console gets passed to the parser. D%4 fails the rigid test of being valid R expression, because a single % is not valid inside an R name (although it would create a token that would be interpreted as a user defined function if there were a closing %) and % is also not a function name (although%% is). The error occurs in the processing of the argument to your function and so it never reached the internal tryCatch-call. I originally didn't get the idea that you wanted to parse this input as R code, so thought that simply wrapping readline as the single argument to be be input may satisfy:
mfun <- function( x=readline(">>+ ") ){ print(x) }
mfun()
#-----screen will display--------
>>+ D%4
[1] "D%4"
If I'm wrong about your intent, as it appears on a re-read of the question, then this would build that input mechanism into your capture_error function. This brings those characters in as unparsed text and then does the parse-eval within the tryCatch enclosure:
> capture_warn_error <- function(x=readline(">>+ ")){
+ tryCatch({ eval(parse(text=x))
+
+ }, warning = function(w) {
+ w
+ }, error = function(e) {
+ e
+ })
+ }
> capture_warn_error(D%4)
Error: unexpected input in "capture_warn_error(D%4)"
> capture_warn_error()
>>+ D%4
<simpleError in parse(text = x): <text>:1:2: unexpected input
1: D%4
^>
> err <- capture_warn_error()
>>+ D%4
> err
<simpleError in parse(text = x): <text>:1:2: unexpected input
1: D%4
^>
> err <- capture_warn_error()
>>+ D %% 4
> err
<simpleError in D%%4: non-numeric argument to binary operator>
> err <- capture_warn_error()
>>+ 4 %smthg% 2
> err
<simpleError in eval(expr, envir, enclos): could not find function "%smthg%">
As demonstrated above, it does require that you not provide any input in the argument list to the function call, but rather make the capture-call with an empty argument list.
You could set up a function to capture input and parse it, wrapping it in your capture_warn_error function.
getfunction <- function(){
x<-readline()
if(x == "exitnow"){return("bye!")}
print(capture_warn_error(eval(parse(text = x))))
getfunction()
}
They'll now be typing at a non-console prompt, but it will work okish - assignments will need work.
1+1
[1] 2
d%e
<simpleError in parse(text = x): <text>:1:2: unexpected input
1: d%e
^>
exitnow
[1] "bye!"
I think this works for capturing the error, although it's a bit convoluted.
a <- try(eval(parse(text="D%4")))

KnitR unable to download documents

I am able to run this code normally in R.
setInternet2(use = TRUE)
download.file("http://d396qusza40orc.cloudfront.net/dsscapstone/dataset/Coursera-SwiftKey.zip", "Coursera-SwiftKey.zip", method = "curl", mode = 'wb')
unzip("Coursera-SwiftKey.zip", files=c("final/en_US/en_US.twitter.txt", "final/en_US/en_US.news.txt", "final/en_US/en_US.blogs.txt"), exdir=".")
But when i try to use knitR it gives me this error
Quitting from lines 15-21 (milestone.Rmd)
Error in parse(text = x, srcfile = src) : <text>:5:106: unexpected ')'
4: unzip("Coursera-SwiftKey.zip", files=c("final/en_US/en_US.twitter.txt", "final/en_US/en_US.news.txt", "final/en_US/en_US.blogs.txt"), exdir=".")
5: file.copy(c("final/en_US/en_US.twitter.txt", "final/en_US/en_US.news.txt", "final/en_US/en_US.blogs.txt"?)
^
Calls: <Anonymous> ... <Anonymous> -> parse_all -> parse_all.character -> parse
Execution halted
I am using R Studio and MAC OS X.
I tried removing the s from https but it still di not work.

Suppress system error with trycatch in R

I am unable to supress the error,though my pdf file is getting converted into text but i am unable to suppress this error.
tryCatch(system(paste("\"", exe, "\" \"", dest, "\"", sep = ""), wait = T))
Syntax Error: Missing or invalid 'Bounds' entry in stitching function
Syntax Error: Missing or invalid 'Bounds' entry in stitching function
Syntax Error: Missing or invalid 'Bounds' entry in stitching function
Syntax Error: Missing or invalid 'Bounds' entry in stitching function
> suppressWarnings(system(paste("\"", exe, "\" \"", dest, "\"", sep = ""), wait = T))
Syntax Error: Missing or invalid 'Bounds' entry in stitching function
Syntax Error: Missing or invalid 'Bounds' entry in stitching function
Syntax Error: Missing or invalid 'Bounds' entry in stitching function
Syntax Error: Missing or invalid 'Bounds' entry in stitching function
>tryCatch(system(paste("\"", exe, "\" \"", dest, "\"", sep = ""), wait = T), error = function(e) e)
Syntax Error: Missing or invalid 'Bounds' entry in stitching function
Syntax Error: Missing or invalid 'Bounds' entry in stitching function
Syntax Error: Missing or invalid 'Bounds' entry in stitching function
Syntax Error: Missing or invalid 'Bounds' entry in stitching function
> suppressMessages(system(paste("\"", exe, "\" \"", dest, "\"", sep = ""), wait = T))
Syntax Error: Missing or invalid 'Bounds' entry in stitching function
Syntax Error: Missing or invalid 'Bounds' entry in stitching function
Syntax Error: Missing or invalid 'Bounds' entry in stitching function
Syntax Error: Missing or invalid 'Bounds' entry in stitching function
> tryCatch(suppressWarnings(capture.output(system(paste("\"", exe, "\" \"", dest, "\"", sep = ""), wait = T))), error = function(e) e)
Syntax Error: Missing or invalid 'Bounds' entry in stitching function
Syntax Error: Missing or invalid 'Bounds' entry in stitching function
Syntax Error: Missing or invalid 'Bounds' entry in stitching function
Syntax Error: Missing or invalid 'Bounds' entry in stitching function
character(0)
> tryCatch({system(paste("\"", exe, "\" \"", dest, "\"", sep = ""), wait = T)}, error = function(e) e)
Syntax Error: Missing or invalid 'Bounds' entry in stitching function
Syntax Error: Missing or invalid 'Bounds' entry in stitching function
Syntax Error: Missing or invalid 'Bounds' entry in stitching function
Syntax Error: Missing or invalid 'Bounds' entry in stitching function
Any reason why am i unable to suppress it ? how can i get rid of this error ?Thanks.
EDIT
With silent=TRUE and function(e){invisible(e)}
tryCatch(system(paste("\"", exe, "\" \"", dest, "\"", sep = ""), wait = T), error = function(e){invisible(e)})
Syntax Error: Missing or invalid 'Bounds' entry in stitching function
Syntax Error: Missing or invalid 'Bounds' entry in stitching function
Syntax Error: Missing or invalid 'Bounds' entry in stitching function
Syntax Error: Missing or invalid 'Bounds' entry in stitching function
> try(system(paste("\"", exe, "\" \"", dest, "\"", sep = ""), wait = T),silent=TRUE)
Syntax Error: Missing or invalid 'Bounds' entry in stitching function
Syntax Error: Missing or invalid 'Bounds' entry in stitching function
Syntax Error: Missing or invalid 'Bounds' entry in stitching function
Syntax Error: Missing or invalid 'Bounds' entry in stitching function
EDITED
It stopped the error but it has also stopped the functionality as well,The pdf file is not getting converted into text by this.
tryCatch(system2(paste("\"", exe, "\" \"", dest, "\"", sep = ""), wait = TRUE,
stdout=TRUE, stderr=TRUE),
error=function(err) NA)
[1] NA
source code
dest=paste("C:/wamp/www/LU/my/pdffiles",file_list[i],sep="/")
exe <- "C:\\Program Files\\xpdfbin-win-3.03\\bin32\\pdftotext.exe"
try(system(paste("\"", exe, "\" \"", dest, "\"", sep = ""), wait = TRUE),
silent=TRUE)
Normally one would write
tryCatch({
system("xyz")
}, error=function(err) {
## do something with 'err', then maybe throw it again stop(err)
## or providing an alternative return value
NA
})
So
> xx = tryCatch(stop("oops"), error=function(err) NA)
> xx
[1] NA
but it seems that some errors thrown by system() cannot be caught in this way.
> xx = tryCatch(system("foobar"), error=function(err) NA)
sh: 1: foobar: not found
The hint that something might be done is from the value of xx:
> xx
[1] 127
The help page first points us to system2() instead, where we see
If 'stdout = TRUE' or 'stderr = TRUE', a character vector giving
the output of the command, one line per character string. (Output
lines of more than 8095 bytes will be split.) If the command
could not be run an R error is generated.
and sure enough
> tryCatch(system2("foobar", stdout=TRUE, stderr=TRUE), error=function(err) NA)
[1] NA
Never actually used tryCatch() before but it seems your error function is error=function(e) e so you are just returning the error you get.
I have used try() in the past with option silent=TRUE to avoid showing the error message. Something like this (disclaimer, the help page for try mentions that using tryCatch may be more efficient):
res=try(runif(Inf), silent=TRUE)
if(class(res)=="try-error") {
print("some error happened")
} else {
print(res)
}
res=try(runif(10), silent=TRUE)
if(class(res)=="try-error") {
print("some error happened")
} else {
print(res)
}
There may be better ways to do this and hopefully others will correct my solution.

overriding R's incomplete error messages

When a call exists of multiple lines, a potential error only includes the first line of match.call() resulting in some lost information and an incomplete sentence. A simple example:
#proper error message:
runif(n=1, k=5)
#incomplete error message:
runif(n=1, k={5})
What would be a way to get R to include the full call to the error message (maybe by collapsing the multiple lines or so)? I am mostly interested in using this in a tryCatch setting.
I had a go at investigating the error object in a tryCatch setting via:
tryCatch( runif(n=1,k={5}),
error = function(e) recover() )
And then selected the 4th environment (value[[3]](cond)) to examine e.
I noticed that e$call was:
Browse[1]> e$call
runif(n = 1, k = {
5
})
So it seems that the error message just uses that first line.
You can collapse all the lines together with:
Browse[1]> paste(deparse(e$call),collapse='')
[1] "runif(n = 1, k = { 5})"
So you could try something like:
tryCatch( runif(n=1,k={5}),
error = function(e) {
cat(sprintf('Error in %s: %s\n',
paste(deparse(e$call),collapse=''),
e$message))
} )
But this doesn't fix up the error message itself, just the call leading up to it:
Error in runif(n = 1, k = { 5}): unused argument(s) (k = {
So the 'Error in xxx' is complete, but the 'unused argument(s) xxx' is still not. It's a start, but not all the way there.
I'm not sure how to improve on this (and am also interested to know if it's possible).

Resources