简体   繁体   中英

I am getting unexpected symbol error when I code a function

Here is the code

reg<-function(y,x){x<-as.matrix(x) x<-cbind(Intercept=1,x) solve(t(x)%*%x)%*%t(x)%*%y} 

Error: unexpected symbol in "reg<-function(y,x){x<-as.matrix(x) x"

I get the same error even when I give line breaks and have spaces between the code elements

This worked for me:

reg<-function(y,x){
     x<-as.matrix(x); 
     x<-cbind(Intercept=1,x);
     solve(t(x)%*%x)%*%t(x)%*%y;
} 

This error is thrown because there is no proper separator after the parse-wise complete statement x<-as.matrix(x) . R's syntax does not recognize a space as a proper separator so the next non-space character needed to be either an end-of-line (EOL) or a semi-colon (;). I see that Travis already showed a code only solution that used end-of-line separators. The one-liner version of your function definiton that would have succeeded is:

reg<-function(y,x){x<-as.matrix(x); x<-cbind(Intercept=1,x); solve(t(x)%*%x)%*%t(x)%*%y}

Note that this doesn't check for semantic correctness in code but is only a statement by the parser that the syntactic rules have been followed. That "unexpected symbol" error message always means that there is an improperly placed or missing parenthesis, curly-brace, semicolon or comma. The actual unexpected symbol in this case was x . You can reproduce the error with:

> x<-as.matrix(x) x
Error: unexpected symbol in "x<-as.matrix(x) x"

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