R automatically executes code following "unexpected symbol"-errors - r

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.

Related

R minus in row name makes name sometimes unaccessible

I have an error I cant recreate with smaller examples so I hope anyone has an idea where to look at.
The problem
As described in the code-comments: rownamesX is not found in the rownames of the matrix (But they are there of course). If I print the not-found names, something like this comes out:
hsa−miR−00
It should be
hsa-miR-00
Further, the I tested some different approaches:
Code works if I source the subscript directly in Rstudio in the console (ctrl-shift-s hotkey)
Code works if I call the function in the Console (Ctrl-Enter on the line)
Code does not work if the subscript is sourced in the main script by (Ctrl-Enter on the line)
Code does not work if the whole main.R is sourced (ctrl-shift-s hotkey)
My environment:
The data matrix
~200k elements
rownames in the form of "type-type2-number"
colnames (=samples) : "S1", "S2", ...
The call:
A main script
sources a subscript
sources a function
calls the function with the data matrix as parameter
The function:
myFunction <- function(rownamesX = c("type-type2-number")
,mat){
indexes <- which(rownames(mat) %in% rownamesX) # This is empty
mat.part <- mat[indexes, ] # therefore his is empty
resp <- mat.part[1, ] - mat.part[2, ] # therefore this yields an error
}
The mistake was quite easy:
There are more than one "-":
−
-
These two look even more equal in Rstudio than here. So I looked for the first(larger) one when the second (smaller) one was in the rowname

Continuation Line error in 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?

Problems with reassignInPackage

I am trying to understand the way the YourCast R package works and make it work with my data.
For example, if a function produces errors, I
get the source code of that function using YourCast:::bad.fn
add outputs of critical
values at critical stages
use reassignInPackage(name="original.fn", package="YourCast", value="my.fn")
Once I find the cause of the error, I fix it in the function and reassign it in the package.
However, for some strange reason this does not work for non-hidden functions.
For example:
install.packages("YourCast")
Library(YourCast)
YourCast:::check.depvar
This will print the hidden function check.depvar. One line if (all(ix == 1:3)) will produce an error message if any of the x is missing.
Thus, I change the whole function to the following and replace the original formula:
mzuba.check.depvar <- function(formula)
{
return (grepl("log[(]",as.character(formula)[2]))
}
reassignInPackage("check.depvar",
pkgName="YourCast",
mzuba.check.depvar)
rm(mzuba.check.depvar)
Now YourCast:::check.depvar will print my version of that function, and everything is fine.
However
YourCast::yourcast or YourCast:::yourcast or simply yourcast will print the non-hidden function yourcast. Suppose I want to change that function as well.
reassignInPackage(name="yourcast",
pkgName="YourCast",
value=test)
Now, YourCast::yourcast and YourCast:::yourcast will print the new, modified version but yourcast still gives the old version!
That might not a problem if I could simply call YourCast::yourcast instead of yourcast, but that produces some kind of error that I can't trace back because suddenly R-Studio does not print error messages at all anymore!, although it still does something if it is capable to:
> Uagh! do something!
> 1 + 1
[1] 2
> Why no error msg?
>
Restarting the R-session will solve the error-msg problem, though.
So my question is: How do I reassign non-hidden functions in packages?
Furthermore (this would faciliate testing a lot), is there a way to make all hidden functions available without using the ::: operator? I.e., How to export all functions from a package?

how to figure out which statement in lapply fails in R

I often have the situation like this:
result <- lapply(1:length(mylist), function(x){
doSomething(x)
})
However, if it fails, I have no idea which element in the list failed on doSomething().
So then I end up recoding it as a for loop:
for(i in 1: length(mylist)){
doSomething(mylist[[i]])
}
I can then see the last value of i and what happened. There must be a better way to do this right?? Thanks!
Notice how the error includes 5L
> lapply(1:10, function(i) if (i == 5) stop("oops"))
Error in FUN(1:10[[5L]], ...) : oops
indicating that the 5th iteration failed.
One simple option is to run the code:
options( error=recover )
before running lapply (see ?recover for details).
Then when/if an error occurs you will instantly be put into the recover mode that will let you examine which function you are in, what arguments were passed to that function, etc. so you can see which step you are on and what the possible reason for the error is.
You can also use try or tryCatch as mentioned in the comments to either skip elements that produce an error or print out information on where they occur.

R "for loop" error messages {}

Since a couple of days ago when I run a for loop in R it gives me plenty of errors related to "}". It only happens if I highlight the whole code and run it. If i execute it line by line, then it runs just fine.
I tried even with the most basic loop:
foo <- seq(1, 100, by=2)
foo.squared <- NULL
for (i in 1:50 ) {
foo.squared[i] <- foo[i]^2
}
Here is the console:
> foo <- seq(1, 100, by=2)
"rror: unexpected input in "foo <- seq(1, 100, by=2)
> foo.squared <- NULL
"rror: unexpected input in "foo.squared <- NULL
> for (i in 1:50 ){
"rror: unexpected input in "for (i in 1:50 ){
> foo.squared[i] <- foo[i]^2
"rror: unexpected input in " foo.squared[i] <- foo[i]^2
> }
Error: unexpected '}' in "}"
>
Details of the R session (I run it in RStudio):
> sessionInfo()
R version 3.0.2 (2013-09-25)
Platform: x86_64-apple-darwin10.8.0 (64-bit)
It has been very annoying!! I would appreciate any advice!!!
Thanks,
Maria
UPDATE:
Here is the code in the very beginning that I suspect causes this problem..It is supposed to take a vector of names and extract the second element from it.
splitnames <- strsplit(as.character(train$Name),"[,.]")
firstelement <- function(x){x[2]}
sapply(splitnames,firstelement)
After I execute it R acts weird. Though I am not 100% sure.
I have been experiencing the same problem, and have found that it is caused by a bug in RStudio (the code runs fine in R and R-gui, but fails in RStudio.) It is hard to reproduce until something gets corrupted in RStudio's saved state, after which the behaviour is pretty consistent.
Removing ~/.rstudio-desktop fixed the issue for me.
mv ~/.rstudio-desktop ~/rstudio-desktop.old
More on resetting RStudio's state on various platforms here.
I suspect that the issue was in using the R script that I downloaded from a website. I ended up reinstalling R and saving my own R script as a new file. I am not sure what and how, but now it is working fine.
I am also using Rstudio and get the same error message when running for loops.
Error: unexpected '}' in "}"
If I source the file, like this...
source('~/.active-rstudio-document')
or if I simply click the "source" button in the GUI, I don't get the same error message.
If sourcing the whole R script is not an option, consider copying the for loop to another file and sourcing that.

Resources