非常基本的 R - 我想编写一个在 R^2 中生成两个向量的函数
Very basic R - I want to write a function that generates two vectors in R^2
我是 R 的新手。我想编写一个在 R^2 中生成两个向量的函数
此函数执行以下操作:
1.It 将这两个 R^2 向量作为两个参数。
2.It 计算两个向量之间的距离和角度。
3.It 将第一个向量投影到第二个向量上。
4.It 可视化投影结果。
我试过代码:
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**
我已经尝试修复我的代码几个小时了,但它仍然没有用。另外,我不知道使用哪个命令来可视化投影结果。谁能帮我解决这个问题?非常感谢!
您打算将其作为单个函数调用吗?也许您最好使用具有多个输入参数的单个函数,而不是多个函数:
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 )
注意:我不会在您的函数中解决任何问题,只会解决它的创建和调用方式。该功能本身对我来说意义不大,所以我不会尝试对其进行编辑。
我是 R 的新手。我想编写一个在 R^2 中生成两个向量的函数 此函数执行以下操作: 1.It 将这两个 R^2 向量作为两个参数。 2.It 计算两个向量之间的距离和角度。 3.It 将第一个向量投影到第二个向量上。 4.It 可视化投影结果。
我试过代码:
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**
我已经尝试修复我的代码几个小时了,但它仍然没有用。另外,我不知道使用哪个命令来可视化投影结果。谁能帮我解决这个问题?非常感谢!
您打算将其作为单个函数调用吗?也许您最好使用具有多个输入参数的单个函数,而不是多个函数:
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 )
注意:我不会在您的函数中解决任何问题,只会解决它的创建和调用方式。该功能本身对我来说意义不大,所以我不会尝试对其进行编辑。