R "for loop" error messages {} - r

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.

Related

Error : Invalid multibyte character in parser at line~

I have a that working well in R ver 3.6.3.
And 1 Weeks ago I download R ver 4.0.0 because I replace my old computer with new one.
Then Suddenly my all code work very poor in R 4.0.0!
When I first search this error, most of people recommend some ways that is related to UTF-8
But What is very annoying is I'm already set my environment! Using Global option tap or else..
I tried to almost everything which is related UTF-8, but It never works.
Also, I tried to update packages tool already but again it never works.
Then Sometimes, I found somethings very strange by chance.
That is,
when I randomly push 'enter' key, suddenly the error didn't pop up!
But I can't find the exact reason why this was happened.
when I paste this code in R ver 3.6.3, It works very nicely! WHAT IS THE REASON!!!
This is same code but, when I tried to execute this code just changing the blank (I mean \r\n(?) \n(?) anyway..) Sometimes the code didn't work, Other times the code works.
This makes me crazy now I don't know the reason
Please help me
The code below is the code what I mentioned until now.
And I attached the picture that is the outcome in R ver 4.0.0
Thank you for reading.
Jeokhap <- function(target_pdf){
target <- target_pdf
page_jeok_1 <- grep("(4.{0,3}|라.{0,3})\\s{0,}이 (집합투자..|투자신탁)에 적합한 투자자 유형",target)
for (k in 1:(length(target)-page_jeok_1)){
if(length(grep("11.{0,3}매입,\\s{0,1}환매",target[(page_jeok_1+k)]))>0){
page_jeok_2 <- page_jeok_1+k
break
}
}
app_list_jeok=c()
for (k in page_jeok_2:page_jeok_1){
app_list_jeok <- append(target[k],app_list_jeok)
}
outcome_jeok <- paste(app_list_jeok,collapse="")
####extract sentence
check_jeok <- gregexpr("(4.{0,3}|라.{0,3})\\s{0,}이 (집합투자..|투자신탁)에 적합한 투자자 유형(.*?)11.{0,3}s{0,1}매입,\\s{0,1}환매",outcome_jeok)
sentence_choose_jeok3 <- regmatches(outcome_jeok,check_jeok)
if(length(regexpr("위험\\s{0,}\\등급\\s{0,}분류\\s{0,}기준",sentence_choose_jeok3))==1){
sentence_choose_jeok3 <- gsub("위험\\s{0,}\\등급\\s{0,}분류\\s{0,}기준.*","",sentence_choose_jeok3)
}else if(length(regexpr("위험\\s{0,}\\등급\\s{0,}분류\\s{0,}기준",sentence_choose_jeok3))>1){
sentence_choose_jeok3 <- sub("(위험\\s{0,}\\등급\\s{0,})(분류\\s{0,})(기준)","\\1\\2의 기준",sentence_choose_jeok3)
sentence_choose_jeok3 <- gsub("위험\\s{0,}\\등급\\s{0,}분류\\s{0,}기준.*","",sentence_choose_jeok3)
}
if(length(regexpr("투자\\s{0,}\\위험\\s{0,}등급\\s{0,}기준",sentence_choose_jeok3))==1){
sth1 <- gsub("투자\\s{0,}\\위험\\s{0,}등급\\s{0,}기준.*","",sentence_choose_jeok3)
}else if(length(regexpr("투자\\s{0,}\\위험\\s{0,}등급\\s{0,}기준",sentence_choose_jeok3))>1){
sentence_choose_jeok3 <- sub("(투자\\s{0,}\\위험\\s{0,})(등급\\s{0,})(기준)","\\1\\2의 기준",sentence_choose_jeok3)
sentence_choose_jeok3 <- gsub("투자\\s{0,}\\위험\\s{0,}등급\\s{0,}기준.*","",sentence_choose_jeok3)
}
return(1)
}

Repeated data.table fread and fwrite causes "Permission denied" error

I encountered this issue using the data.table fwrite() and fread() functions for managing resources in a parallel calculation, but was also able to recreate the behavior in the below sequential example code. Calling fwrite() throws the following error:
Error in fwrite(dt, csv_path) : Permission denied: 'D:/mypath/test.csv'. Failed to open
existing file for writing. Do you have write permission to it? Is this
Windows and does another process such as Excel have it open?
The behavior seems to be related to the calling of fread() right before, as commenting out the fread() command makes the error disappear. Depending on your system, you might have to increase the number of iterations before the error occurs as it occurs at varying iteration numbers.
Does anyone have an idea why this is happening? Thanks in advance for your assistance!
Example code:
library(data.table)
dt = data.table(a = c(1, 2), b = c("a", "b"))
csv_path = "D:/mypath/test.csv"
fwrite(dt, csv_path)
for(i in 1:10000){
test = fread(csv_path)
fwrite(dt, csv_path)
}
System info
R version 4.0.0 (2020-04-24)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows Server x64 (build 14393)
data.table_1.12.8
I tried your code on a Windows machine and I was not able reproduce it.
I believe the issue is related to Windows file handler, which seems to be not fast enought to close file connection before opening it again.
You can try following code to see if it is reproducible just in R:
x = "a,b\n1,a\n2,b\n"
csv_path = "D:/mypath/test.csv"
file.create(csv_path)
f = file(csv_path, "w")
cat(x, file=f)
close(f)
for (i in 1:10000) {
f = file(csv_path, "r")
test = readLines(f)
close(f)
f = file(csv_path, "w")
cat(x, file=f)
close(f)
}
What could also make sense is it see how much Sys.sleep is enough to make the problem disappear.
Determine the number of threads you're using for data tables with
data.table::getDTthreads()
I was receiving the same fread() error until I reduced this from 96 to 24 with
data.table::setDTthreads(threads = 24)
Other users have reported threads < 79 works. See .data.table crashes with segfault while grouping with more than 79 threads #5077.

Stopping R code execution upon error when run as non-interactive Rscript

How do I get an R (version 3.4.2, CentOS 6.9) script to stop on Error instead of happily continuing on? My file :
$ cat tmp.R
a = 9
print(a)
print(b)
print(d)
print("Should never get here")
Running tmp.R non-interactively it:
$ Rscript tmp.R
Looking for libraries in : ~/.R/3.4.2-lib
[1] 9
Error in print(b) : object 'b' not found
Error in print(d) : object 'd' not found
[1] "Should never get here"
Question : How do I get R to stop execution upon encountering an error?
I've tried things like options(error=stop) and options(error=browser) which work in the interactive case but not non-interactive Rscript example.
This is because I have set options(error=traceback) in my .Rprofile. Commenting it out in my .Rprofile leads to code termination at line 3 as expected. This raises issues with why this generates output. See related questions this and this.

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.

R Studio running scripts improperly? [duplicate]

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