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