简体   繁体   中英

Function that calculates Euclidean distance in R

I want to create a function which has two inputs each of which are a vector of real numbers and outputs the Euclidean distance between the two vectors. I'd like to know how to do this. This is what I've tried so far;

distance<-function(A=c(x1,y1),B=c(x2,y2)){
+  +return(dist(A,B,method="euclidean"))
}
distance(c(-2,1),c(2,6))

Running this gives :

> distance<-function(A=c(x1,y1),B=c(x2,y2)){
+   return(dist(A,B,method="euclidean"))
+ }
> distance(c(-2,1),c(2,6))
  1 2
1 0  
2 3 0
Warning message:
In if (!diag) cf[row(cf) == col(cf)] <- "" :
  the condition has length > 1 and only the first element will be used

Trying

    distance<-function(A=c(x1,y1),B=c(x2,y2)){
  +return(sqrt((y2-y1)^2+ (x2-x1)^2))
}
distance(c(-2,1),c(2,6))

yields

+   +return(sqrt((y2-y1)^2+ (x2-x1)^2))
+ }
> distance(c(-2,1),c(2,6))
Error in distance(c(-2, 1), c(2, 6)) : object 'y2' not found

I'm unsure why the error object y2 not found is occurring.

You can't assign variables inside a vector as an argument, you can only assign a 1x2 vector and use [] to access its contents.

distance<-function(A, B){
  return(sqrt((A[1]-A[2])^2+ (B[1]-B[2])^2))
}

distance(c(-2,1),c(2,6))
> [1] 5

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM