2016-10-10 21 views
-1

我是R中的新手。我想編寫一個函數,在R^2中生成兩個向量 此函數執行以下操作: 1.將這兩個R^2向量作爲兩個參數。 2.計算兩個向量之間的距離和角度。 3.將第一個矢量投影到第二個矢量上。 4.可視化投影結果。非常基本的R - 我想寫一個函數,在R^2中生成兩個向量

我試過代碼:

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

我試圖解決我的幾個小時的代碼,它仍然沒有奏效。另外,我不知道使用哪個命令來顯示投影結果。任何人都可以幫助我嗎?我真的很感激!

+1

當你將代碼輸入到R中時,如果你的代碼行沒有完成,並且R在同一個表達式中需要更多的代碼,你會在控制檯看到一個'+'。當上一行完成並且R準備好新的表達式時,您將看到'>'。當你說'x < - function(x)'你正在創建一個名爲'x'的新函數時,R期望該函數的定義遵循。但是,你的下一行是'y < - function(y)'。看起來你可能想要像'my_function < - function(x,y){<函數定義>}這樣的東西。 – Gregor

+0

所以,最大的問題是前兩行。你試圖將x和y定義爲函數,但是在R語法中,解釋器正在等待函數定義 – Shape

+0

謝謝!我知道了! :) – sunnypy

回答

1

您打算將此稱爲單一功能嗎?

output <- func(x, y) 

或者更明確:

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 = x, y = y) 

注意:我沒有處理函數中的任何內容,只是它創建和調用的方式。該函數本身對我來說沒有多大意義,所以我不會試圖編輯它。

+0

謝謝!我看到問題在哪裏:) – sunnypy

相關問題