I noticed that, in some cases (I am still a beginner at R!), multi lines instructions cannot be merged 'as is' into simple lines instructions. Let's take an example, which is in a lesson I recently had on line:
> make.power <- function(n) {
+ pow <- function(x) {
+ x^n
+ }
+ pow
+ }
Is the definition of the 'make.power' function. I can then define the 'cube' or the square functions
> cube <- make.power(3)
> square <- make.power(2)
Then, if I try to define make.power on a single line with exactly the very same syntax:
> make.power <- function(n) { pow <- function(x) { x^n } pow }
This will raise an "Unexpected symbol in "make.power ...". This said, the following single line code will work:
> make.power <- function(n) { pow <- function(x) { x^n }}
and, when switched to multi-line, will still work!
> make.power <- function(n) {
+ pow <- function(x) {
+ x^n
+ }
+ }
I must admit that I am quite confused. My questions are the following:
- Why can't I just merge the multi-line code in a single line instruction?
- In the first multi-line definition of the function, why should one recall the 'pow' function right after the function is defined, which is obviously of no interest, as the same code without the recalling is ok!
Edit: following #Dwin answer, it is true that the following expression:
> make.power <- function(n) { pow <- function(x) { x^n }; pow }
works perfectly. And so does this one:
> make.power <- function(n){; pow <- function(x) {; x^n }; pow }
So it seems that the ";" could be mandatory in some cases (here, between the "}" and second 'pow', and not in other cases (between the '{' and first 'pow')?