Question

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.

No correct solution

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top