-1

I'm new in R. And I want to write a function that generates two vectors in R^2 And this function does the following: 1.It takes these two R^2 vectors as the two arguments. 2.It calculates the distance and angle between the two vectors. 3.It projects the first vector onto the second vector. 4.It visualize the projection result.

I tried the codes:

x <- function(x)
y <- function(y)
distance <- (sqrt(sum(x*x))*sqrt(sum(y*y)))
theta <- -acos(sum(x*x)/distance)
proj <- (x%*%y)/norm(y)%*%y
if (length(x)==2 & length (y) ==2)
{ print(distance) &
print(theta) &
print(proj)      
}else {
print("Not R^2 vectors")
}  

And I got the error message:

> x <- function(x)
+ y <- function(y)
+ distance <- (sqrt(sum(x*x))*sqrt(sum(y*y)))
> theta <- -acos(sum(x*x)/distance)
**Error in x * x : non-numeric argument to binary operator**
> proj <- (x%*%y)/norm(y)%*%y
**Error: object 'y' not found**
>   if (length(x)==2 & length (y) ==2)
+   { print(distance) &
+     print(theta) &
+     print(proj)
+       
+   }else {
+     print("Not R^2 vectors")
+   }
**Error: object 'y' not found**    

I've tried to fix my code for hours and it still didn't work. Also, I don't know which command to use to visualize the projection result. Could anyone please help me with this? I'd really appreciate that!

sunnypy
  • 11
  • 2
  • 1
    When you enter code into R, you will see a `+` at the console if your line is unfinished and R is expecting more code in the same expression. You will see `>` when the previous line is complete and R is ready for a new expression. When you say `x <- function(x)` you are creating a new function named `x`, and R expects the definition of that function to follow. But instead your next line is `y <- function(y)`. It seems like you probably want something like `my_function <- function(x, y) { }`. – Gregor Thomas Oct 10 '16 at 03:50
  • So, the big issue is the first 2 lines. you're trying to define x and y as functions, but in R syntax, the interpreter is waiting for a function definition afterwards – Shape Oct 10 '16 at 03:51

1 Answers1

1

Are you planning to call this as a single function? Maybe you'd be better served with a single function with multiple input parameters, rather than multiple functions:

func <- function(x, y) {
    distance <- (sqrt(sum(x*x))*sqrt(sum(y*y)))
    theta <- -acos(sum(x*x)/distance)
    proj <- (x%*%y)/norm(y)%*%y
    if (length(x)==2 & length (y) ==2)
    { print(distance) &
            print(theta) &
            print(proj)      
    }else {
        print("Not R^2 vectors")
    }  
}

So you'd call it with something like:

output <- func( x, y )

Or, perhaps more clearly:

output <- func( x = x, y = y )

Note: I'm not addressing anything within your function, only the way it's created and called. The function itself doesn't make a lot of sense to me, so I won't try to edit that.

rosscova
  • 5,430
  • 1
  • 22
  • 35