sunnypy - 8 months ago 47

R Question

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!

Answer

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.

Source (Stackoverflow)