Link to home

Writing Functions

You can create new custom functions in R to do more complicated calculations.

As a simple example, suppose you want to write a function that will return the squared value of whatever value you enter into the function. You can create such a function with the following command.

square.it <- function(x){x^2}

 

Note that those are curly brackets around x^2. Here x is used temporarily and the intention is not usually to have an object named x read in, though that is what will happen if no value for x is specified when the function is applied (which can lead to confusion). Try these commands, checking the value of x and y98 after each command.

x <- 2
y98 <- square.it(x=5)
y98 <- square.it(x)
y98 <- square.it(x=3)

 

Note that the value in the object x does not change when the function is applied, unless the output of the function is assigned to x.

x <- square.it(x=5)

 

More complicated functions can be made that include multiple lines of commands split by a semi-colon or on separate lines. The variables created inside the function, temp1 and temp2, are also just used temporarily.

fun91 <- function(x, y){temp1 <- x*y; temp2 <- log10(temp1); temp2}

 

Or, equivalently, to make the function easier to read:

fun91 <- function(x, y){
temp1 <- x*y
temp2 <- log10(temp1)
temp2
}

 

This example gives the value in temp2 as output. Try:

fun91(x=10, y=100)

 

The function can be applied to any objects x and y that make sense. For example:

fun91(x=c(1, 2), y=c(10, 100))

 

The function can also be applied to pre-existing objects.

z1 <- c(1, 2)
z2 <- c(10, 100)
fun91(x=z1, y=z2)

 

Next: Closing a Session