Continuation Line error in R - r

This feels like a very simple question, but I can't find an answer anywhere I've searched. I'm new to R and when I try to break up my code across several lines with ctrl+shift+enter, but I don't get the '+' that should start the line in the console, and I get an error message when I try to run it. Sample code is:
for (j in 1:length(codes)) {
currCountry <- subset(currRegion, Country.Code == codes[j])
currCountry <- currCountry[order(currCountry$variable, decreasing=FALSE),]
lines(1960:2009, currCountry$value, col="#00200070", lwd=0.8)
}
I get the following error:
Error: unexpected input in "for (j in 1:length(codes)) {‚"
If I copy the same code from the online tutorial I'm doing, it works fine, but each line starts with a '+'. What can I do to get this?

Related

Why am I receiving "plow.new has not been called yet" when trying to plot PCAs?

This is the end goal however when trying to plot the code below
plot(PCAloadings[,1:2], arrows(0,0,PCAloadings[,1],PCAloadings[,2]), text(PCAloadings[,1:2], labels=rownames(PCAloadings))
I recieve the following error:
in text.default(PCAloadings[, 1:2], labels = rownames(PCAloadings)) : plot.new has not been called yet
I am unsure how to resolve this issue or what it pertains to, any help is welcome.
EDIT: when trying to run line by line only the first line runs. When trying to run arrows or text lines I run into the same error
plot(PCAloadings[,1], PCAloadings[,2])
This is the output from the first line alone
Seems to be a syntax problem. Try
plot(PCAloadings[,1:2])
arrows(0,0,PCAloadings[,1],PCAloadings[,2])
text(PCAloadings[,1:2], labels=rownames(PCAloadings))

is there a way to make the for loop run a command like this?

i have some datasets named f1998-f2005 and i wanna use looping to run the following commands because it is a hassle to type line after lines of commands, i tried running the following codes to make it more automated:
for (i in 1998:2005) {
model.poissqmle.f1.199(i) <- glm(formula1, data=f199(i), family=quasipoisson()
print (summary(model.poissqmle.f1.199(i)))
}
but r returned me the following message:
Error: unexpected '}' in:
" + print (summary(model.poissqmle.f1.199(i)))
}"
Thanks for your help, my foundations in R is really weak but i have to use it for one of my research now hence i would really appreciate a kind soul to help me out. Thanks!

R automatically executes code following "unexpected symbol"-errors

in recent months i realized a very annoying behaviour on both windows and unix R with R-Studio installations.
After an error, R is auto-executing every code it finds following a line producing an error(here: "unexpected symbol"). Here is an example code
vec1 <- c("Hallo", "World"
vec2 <- c(1,2,3)
print(vec2)
print(vec1)
In the first line:
vec1 <- c("Hallo", "World"
R is missing a closing ")". After erronously initializing it, this happens:
vec1 <- c("Hallo", "World"
+
+ vec2 <- c(1,2,3)
Error: unexpected symbol in:
"
vec2"
>
> print(vec2)
Error in print(vec2) : object 'vec2' not found
>
> print(vec1)
Error in print(vec1) : object 'vec1' not found
>
R apparently does try to look for a closing bracket, finds one, gives the expected "Unexpected symbol"-error, but instead of stopping it does try to execute the next line (and everything else following) as well.
Is this R- or R-Studio related and how can i stop that?
edit:
I should clarify what the problem is, based on the comments. This behaviour is not intended, nor did i plan to include faulty lines to my code!
Sometimes one just forgets to add a bracket, or comma, or whatever, but still initializes such a line. Then - at least for me - R has this very annoying behaviour to then run through the entire code. Here is a real life example:
Somewhat later in the same situation, model objects were written over, which was very annoying.
So again, i dont want you to correct the code, i would like to learn why R behaves as descrined and how to stop it.
It sounds like you're expecting R to stop when it finds an error. After all, that's what traditional compiled languages like C and Java do. But R isn't a compiled language. Each line of code is interpreted in order. This is an inherent part of R and doesn't have anything to do with RStudio. In your example, it's really hard for R to figure out where the call to c() ends because you're missing the close parenthesis.
One RStudio feature that I find useful for preventing this specific type of error is the auto-formatter (CTRL-SHIFT-A). When formatting the code sample you provide, it becomes obvious that something's not right when you look at the indentation.
The code changes from this...
vec1 <- c("Hallo", "World"
vec2 <- c(1, 2, 3)
print(vec2)
print(vec1)
To this..
vec1 <- c("Hallo", "World"
vec2 <- c(1, 2, 3)
print(vec2)
print(vec1)
The fact that the bottom three lines are indented so far to the right gives me a warning that I might have missed a closing parenthesis.
Generally
If your question is about broader error handling, you can often use a function to prevent R from continuing when it encounters an error. This won't work with your example since the parentheses are wrong, but it gives an answer to the broader question of when you can get R to stop upon encountering a problem.
Let's generate an error.
stop("This is an error")
print("The code keeps running!")
Notice how the second line runs after the error. Now let's wrap that code in a function.
demo_function <- function() {
stop("This is an error")
print("The code keeps running!")
}
demo_function()
The function throws an error and halts execution.
It's a good idea to put high-risk code inside of a function for exactly this reason. With the example you provided, R will throw an error as soon as you try to define the function, which might help you catch an error earlier in the development process.
As per the customer support of R-Studio, this behaviour is related to R-Studio and can be stopped by unticking "Execute all lines in a statement" under Global Options -> Editing -> Execution. Sorry for bothering.
You have to add some commas (' , ') and some parenthesis to your syntax, try with:
> vec1 <- c("Hello", "World")
> vec2 <- c(1,2,3)
> print(vec2)
> print(vec1)
It should work.

catching an exception on R getGEO

I am using R and the GEOQuery package for downloading a set of GEO profiles. For doing this I use the following instructions:
library(Biobase)
library(GEOquery)
gdsAcc<-getGEO('GDS1245',destdir=".")
which downloads the GDS1245.soft.gz in the specified directory.
The problem is that some GEO profiles have been removed, so when I use the above mentioned instructions in a loop and I came with something like:
gdsAcc<-getGEO('GDS450',destdir=".")
in the last case the profile GDS450 does not exist so it throws an error and the program stops. I would like to know how I can catch that error so that in case that the profile does not exist the program will continue looking for the other profiles.
My algorithm is something like:
for (i in 1:length_GEO_profiles){
disease<-GEOname
gdsName<-paste("GDS",disease,sep="")
gdsAcc<-getGEO(gdsName,destdir=".")
}
Any help?
Thanks
You should look at try and tryCatch. Here's an example to get you started:
for(i in 1:3) {
if(i == 1)
gdsAcc <- try(getGEO('GDS450',destdir="."))
cat(i, "\n")
}
If you want to do something with the error, then use an if statement:
if(class(gdsAcc) == "try-error") cat("HELP")
Related questions
Exception handling in R
Equivalent of "throw" in R
catching an error and then branching logic

tryCatch does not catch an error if called though RScript

I'm facing a strange issue in R.
Consider the following code (a really simplified version of the real code but still having the problem) :
library(timeSeries)
tryCatch(
{
specificWeekDay <- 2
currTs <- timeSeries(c(1,2),c('2012-01-01','2012-01-02'),
format='%Y-%m-%d',units='A')
# just 2 dates out of range
start <- time(currTs)[2]+100*24*3600
end <- time(currTs)[2]+110*24*3600
# this line returns an empty timeSeries
currTs <- window(currTs,start=start,end=end)
message("Up to now, everything is OK")
# this is the line with the uncatchable error
currTs[!(as.POSIXlt(time(currTs))$wday %in% specificWeekDay),] <- NA
message("I'm after the bugged line !")
},error=function(e){message(e)})
message("End")
When I run that code in RGui, I correctly get the following output:
Up to now, everything is OK
error in evaluating the argument 'i' in
selecting a method for function '[<-': Error in
as.POSIXlt.numeric(time(currTs)) : 'origin' must be supplied
End
Instead, when I run it through RScript (in windows) using the following line:
RScript.exe --vanilla "myscript.R"
I get this output:
Up to now, everything is OK
Execution interrupted
It seems like RScript crashes...
Any idea about the reason?
Is this a timeSeries package bug, or I'm doing something wrong ?
If the latter, what's the right way to be sure to catch all the errors ?
Thanks in advance.
EDIT :
Here's a smaller example reproducing the issue that doesn't use timeSeries package. To test it, just run it as described above:
library(methods)
# define a generic function
setGeneric("foo",
function(x, ...){standardGeneric("foo")})
# set a method for the generic function
setMethod("foo", signature("character"),
function(x) {x})
tryCatch(
{
foo("abc")
foo(notExisting)
},error=function(e)print(e))
It seems something related to generic method dispatching; when an argument of a method causes an error, the dispatcher cannot find the signature of the method and conseguently raises an exception that tryCatch function seems unable to handle when run through RScript.
Strangely, it doesn't happen for example with print(notExisting); in that case the exception is correctly handled.
Any idea about the reason and how to catch this kind of errors ?
Note:
I'm using R-2.14.2 on Windows 7
The issue is in the way the internal C code implementing S4 method dispatch tries to catch and handle some errors and how the non-interactive case is treated in this approach. A work-around should be in place in R-devel and R-patched soon.
Work-around now committed to R-devel and R-patched.
Information about tryCatch() [that the OP already knew and used but I didn't notice]
I think you are missing that your tryCatch() is not doing anything special with the error, hence you are raising an error in the normal fashion. In interactive use the error is thrown and handled in the usual fashion, but an error inside a script run in a non-interactive session (a la Rscript) will abort the running script.
tryCatch() is a complex function that allows the potential to trap and handle all sorts of events in R, not just errors. However by default it is set up to mimic the standard R error handling procedure; basically allow the error to be thrown and reported by R. If you want R to do anything other than the basic behaviour then you need to add a specific handler for the error:
> e <- simpleError("test error")
> tryCatch(foo, error = function(e) e,
+ finally = writeLines("There was a problem!"))
There was a problem!
<simpleError in doTryCatch(return(expr), name, parentenv, handler): object 'foo'
not found>
I suggest you read ?tryCatch in more detail to understand better what it does.
An alternative is to use try(). To modify your script I would just do:
# this is the line with the uncatchable error
tried <- try(currTs[!(as.POSIXlt(time(currTs))$wday %in% specificWeekDay),] <- NA,
silent = TRUE)
if(inherits(tried, "try-error")) {
writeLines("There was an error!")
} else {
writeLines("Everything worked fine!")
}
The key bit is to save the object returned from try() so you can test the class, and to have try() operate silently. Consider the difference:
> bar <- try(foo)
Error in try(foo) : object 'foo' not found
> bar <- try(foo, silent = TRUE)
> class(bar)
[1] "try-error"
Note that in the first call above, the error is caught and reported as a message. In the second, it is not reported. In both cases an object of class "try-error" is returned.
Internally, try() is written as a single call to tryCatch() which sets up a custom function for the error handler which reports the error as a message and sets up the returned object. You might wish to study the R code for try() as another example of using tryCatch().

Resources