R for Spatial Statistics

 

Functions

Creating your own functions is easy in R.

Writing Functions

To write your own functions you just assign the function to a variable using the function() function. Parameters are specified in the call to function(). Note that when you run a function it will appear in the Functions pane in RStudio. You only have to run a function once and then it will be available to your other R code.

PrintSeries = function (N) 
{
	for(i in 1:N)
	{
		y = i*i
		print(y)
	}
}

Now you can call your function:

PrintSeries(12)

Functions that Return Values

You can also return a value from a function so you can create functions to compute values. The function below will convert a US Foot value to meters and return it:

FeetToMeters = function (DistanceInFeet) 
{
	DistanceInMeters=DistanceInFeet*0.3048
	return(DistanceInMeters)
}

Now, you can call this function to obtain a value:

DistanceInMeters=FeetToMeters(DistanceInFeet)