The
apply()
function is an alternative to writing loops, via applying a function to columns, rows, or individual values of an array or matrix.
The structure of the apply()
function is:
apply(X, MARGIN, FUN, ...)
The matrix variable used for the exercises is:
dataset1 <- cbind(observationA = 16:8, observationB = c(20:19, 6:12))
Answers to the exercises are available here.
Exercise 1
Using apply()
, find the row means of dataset1
Exercise 2
Using apply()
, find the column sums of dataset1
Exercise 3
Use apply()
to sort the columns of dataset1
Exercise 4
Using apply()
, find the product of dataset1
rows
Exercise 5
Required function:
DerivativeFunction <- function(x) { log10(x) + 1 }
Apply “DerivativeFunction
” on the rows of dataset1
Exercise 6
Re-script the formula from Exercise 5, in order to define “DerivativeFunction
” inside the apply()
function
Exercise 7
Round the output of the Exercise 6 formula to 2 places
Exercise 8
Print the columns of dataset1
with the apply()
function
Exercise 9
Find the length of the dataset1
columns
Exercise 10
Use apply()
to find the range of numbers
within the dataset1
columns
Wow, exercise #3 not only shows how to sort your data, it even improves the correlation between the two variables from .42 to .93! This type of sorting variables independent of one another destroys the covariance in the data. A tip for beginners: use the order function to sort data sets, or use the arrange function from the dplyr package. The latter is easier to learn.
Thanks for your comment, Bob. We address sorting data in this set: http://r-exercises.com/2016/03/01/get-your-stuff-in-order-exercises/
Thank you very much – a great intro to using apply(), something I’ve been loathe to use as it looked too complicated.
Will you be doing exercises for the other apply functions (e.g. lapply, sapply)?
Thanks, Ben! Yes, the next set of exercises that I will post, will cover the other apply functions in R.