Basic programming: Defining functions
Default values for arguments of a function
You can give some function arguments a default value so that you can omit them in a function call. Consider the following example of a distance function
The Euclidean distance between two points \((x_1,y_1)\) and \((x_2,y_2)\) is given by \[\text{distance}=\sqrt{(x_1-x_2)^2+(y_1-y_2)^2}\] We define the function distance
that calculates the distance between two points and in case there is only one point as an argument in a call to this function uses the default value \((0,0)\) for the second point. We use the coordinates of the points as 4 arguments to the function.
The R script
distance <- function(P1.x, P1.y, P2.x=0, P2.y=0) {
return( sqrt((P1.x-P2.x)^2+(P1.y-P2.y)^2) )
}
cat("distance between (1,2) and (3,4) =", distance(1,2,3,4), "\n")
cat("distance between (1,2) and (3,4) =", distance(1,2,4, P2.x=3), "\n")
cat("distance between (1,2) and (3,0) =", distance(1,2,1), "\n")
cat("distance between (1,2) and (0,0) =", distance(1,2), "\n")
yields the following result:
distance between (1,2) and (3,4) = 2.828427 distance between (1,2) and (3,4) = 2.828427 distance between (1,2) and (3,0) = 2 distance between (1,2) and (0,0) = 2.236068
Unlock full access