# rturf 5: writing a function, and using ifelse

It is convenient to write functions that will make calculations or produce specific output. In this rturf screencast, I demonstrate the creation of a `brede` function that when given two inputs, which should be the uphill and downhill ball roll distances in inches, returns the green speed in feet.

``````# function to calculate green speed by Brede equation, input is in inches
brede <- function(a, b) {
speed <- (2 * a * b) / (a + b) / 12
return(speed)
}
``````

That function is given the name `brede`, and it has two inputs, which I called a and b. They could have been x and y, or u and d, or uphill and downhill, or roll1 and roll2. They represent the uphill and downhill direction of ball roll when using the stimpmeter. When that function is used, it returns the green speed in feet after applying the Brede correction.

I also showed the `ifelse` function by correcting the stimpmeter measurements that were made from the 2x notch.

``````d\$speed1 <- ifelse(d\$x1x2 == 2, d\$speed * 2, d\$speed)
``````

The `d` data frame has a column named `x1x2` with integer values of 1 or 2 in it. If the value is 1, it means the measurements in that row were taken by rolling the balls from the standard notch on the stimpmeter. If the value is 2, the measurements in that row represent balls that were rolled from the short notch, and the green speed calculated from those rolls should be multiplied by two.

I find the `ifelse` function useful to make these type of corrections.

It evaluates the value of `x1x2` in each row of the data frame to determine if the value is 2. If the value is 2—meaning the balls were rolled from the short notch and the calculated green speed must be multiplied by two—then the new `speed1` variable will be the green speed multiplied by two. However, if the value of `x1x2` is not 2, then the `speed1` variable will be the green speed already calculated, and won’t be multiplied by two.