简体   繁体   中英

Unexpected symbol in function (R language)

I'm trying out the following piece of code from the book "The Art of R Programming" and for some reason I get the error message "Error: unexpected symbol in "first1 <- function(x) {for (i in 1:length(x)) {if (x[i] == 1) break} return" This code is exactly as shown in the book (except that I'm unable to split each line on its own line).

The function seems to work fine when I remove return(i).

first1 <- function(x) {for (i in 1:length(x)) {if (x[i] == 1) break} return(i) }

The semicolon is neccessary to separate individual commands, in the case the for loop and the return commands:

first1 <- function(x) {for (i in 1:length(x)) {if (x[i] == 1) break}; return(i) }

but rather use the structured form of code:

first1 <- function(x) {
  for (i in 1:length(x)) {
    if (x[i] == 1) break
  } 
  return(i) 
  }

If you had entered just this at the R console you would not have gotten the error. The R-parser would have known htat it was an incomplete expression and it would have entered the line-break for you and indicated that it was waiting for the expression to be completed by putting a plus-sign on the far left of the screen:

first1 <- function(x) {for (i in 1:length(x)) {if (x[i] == 1) break}
+  # that was displayed by the R interpreter/parser

You would have then been able to complete the command with:

return(i) }

And when you hit <enter> there would now be a function named first1 in the global environment. The usual way to interact with R is to first build your code in an editor. The GUI's and IDE's for R usually provide such capacity. Rstudio is a particularly popular one, but there are several others available.

Here's what appears at my console when I enter a multi-line function.

> f_e<-function(){
+     b=2
+     c=2
+     d=eval( (expr_list()$f_a))
+     print(d)
+ }

But if I copy and paste that exactly into the interpreter I'll get an error because neither ">" nor the "+"'s are really part of the code. They're just messages to the user. I would need to paste in:

f_e<-function(){
     b=2
     c=2
     d=eval( (expr_list()$f_a))
     print(d)
 }

(I think the R-GUI in the Windows version of R might accept the text with the ">" and "+" 's and strip them as a convenience, but my system does not.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM