-1

我是 R 的新手。我想编写一个在 R^2 中生成两个向量的函数,这个函数执行以下操作: 1.它将这两个 R^2 向量作为两个参数。2.计算两个向量之间的距离和角度。3.它将第一个向量投影到第二个向量上。4.投影结果可视化。

我尝试了以下代码:

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")
}  

我收到错误消息:

> 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**    

我已经尝试修复我的代码几个小时,但它仍然没有工作。另外,我不知道使用哪个命令来可视化投影结果。谁能帮我解决这个问题?我真的很感激!

4

1 回答 1

1

您打算将其称为单个函数吗?也许您最好使用具有多个输入参数的单个函数,而不是多个函数:

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")
    }  
}

所以你可以这样称呼它:

output <- func( x, y )

或者,也许更清楚:

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

注意:我没有在你的函数中解决任何问题,只是它的创建和调用方式。该函数本身对我来说没有多大意义,所以我不会尝试对其进行编辑。

于 2016-10-10T02:52:43.220 回答