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

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

Related

R Url function on Mac

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

R Markdown does not run

I tried to run my script in R Markdown. It does not run and gives the error below:
Quitting from lines 15-139 (m.Rmd)
Erro em $<-.data.frame(*tmp*, "efavirens", value = integer(0)) :
replacement has 0 rows, data has 5794
Calls: ... withVisible -> eval -> eval -> $<- -> $<-.data.frame
Execu��o interrompida
The following is a part of the script:
```{r, echo=FALSE}
suicidio <- read.csv2("E:/Spss/suicidio4.csv",header=T,sep=";")
str(suicidio)
suicidio<-subset(suicidio,desfecho != 9)
suicidio2<-subset(suicidio,Desfecho2 != 9)
suicidio$tempo<-as.numeric(suicidio$tempo)
suicidio$dias_inicio[suicidio$dias_inicio_cont == "#NULO!"]<-NA
suicidio$dias_fim[suicidio$dias_fim_cont == "#NULO!"]<-NA
suicidio$cor[suicidio$A19_COR == "#NULO!"]<-NA
suicidio$sexo<-factor(suicidio$sexo)
suicidio$cor<-factor(suicidio$cor)
suicidio$obito<-factor(suicidio$obito)
suicidio$escol2<-factor(suicidio$escol3)
suicidio$idade_hiv_cat<-factor(suicidio$idade_hiv_cat2)
suicidio$idade_hiv_cat<-factor(suicidio$idade_dtfim_cat)
suicidio$acomp_regular<-factor(suicidio$acomp_regular)
suicidio$drogas<-factor(suicidio$drogas)
suicidio$alcool<-factor(suicidio$alcool)
suicidio$efavirens<-factor(suicidio$efavirens)
suicidio$epilepsia<-factor(suicidio$epilepsia)
suicidio$tentativa<-factor(suicidio$tentativa)
suicidio$causa_externa<-factor(suicidio$causa_externa)
suicidio$causa_externa<-factor(suicidio$transgen)
suicidio$causa_externa<-factor(suicidio$cate_expo2)
suicidio$causa_externa<-factor(suicidio$etnia
)
library(survival)
y<-Surv(suicidio$tempo,suicidio$desfecho)
Can someone help me?
This is not a R Markdown error, this is an R error, telling you that you have a bug in your R code. Run the script line by line (CTRL+Enter is a good shortcut) and see which one gives the error. It is basically saying that you are trying to overwrite a column with 5794 cells/rows with a vector that has no data in it (something where length(x) would yield 0; printing the object would report factor(0) or character(0), or whatever the data type).

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.

Error: Error in file(con, "r") : cannot open the connection

I am trying to run dssp function using bio3d package in R. But I am getting error.
library("bio3d")
pdb <- read.pdb("1CRN")
x <- dssp(pdb, exepath="C:/dssp/dssp.exe")
Error in file(con, "r") : cannot open the connection
Any suggestions please.
To solve it you need to fix the dssp function paramenters:
fix(dssp)
rewrite the following line:
system(paste(exepath, "dssp -c ", infile, " ", outfile, sep = ""), ignore.stderr = TRUE)
"-i" istead of "-c" and "-o" intead of " "
chears

Resources