Looping on the command line in R can be done using the following functions:
lapply(): This function loops over a list and evaluates a function on each element. For example, the following code will loop over the list `my_list` and print the length of each element:
my_list = list(1, 2, 3, 4, 5)
lapply(my_list, length)
sapply(): This function is similar to `lapply()`, but it tries to simplify the result. For example, the following code will loop over the list `my_list` and print the length of each element, but it will also try to simplify the result to a scalar value.
my_list = list(1, 2, 3, 4, 5)
sapply(my_list, length)
apply(): This function applies a function to the margins of an array. For example, the following code will calculate the mean of each column in the matrix `my_matrix`
my_matrix = matrix(1:20, nrow = 5, ncol = 4)
apply(my_matrix, 2, mean)
tapply(): This function applies a function to subsets of a vector. For example, the following code will calculate the mean of each unique value in the vector `my_vector`:
my_vector = c(1, 2, 2, 3, 3, 4, 4, 5)
tapply(my_vector, my_vector, mean)
mapply(): This function is a multivariate version of `lapply()`. It can be used to apply a function to multiple vectors or lists. For example, the following code will calculate the mean of each element in the list `my_list` and the list `my_other_list`:
my_list = list(1, 2, 3, 4, 5)
my_other_list = list(6, 7, 8, 9, 10)
mapply(mean, my_list, my_other_list)
These are just a few of the functions that can be used for looping on the command line in R.
Note
- Use the `break` statement to exit a loop early.
- Use the `next` statement to skip to the next iteration of a loop.
- Use the `while` loop to repeat a block of code as long as a certain condition is met.
- Use the `repeat` loop to repeat a block of code until a `break` statement is encountered.
- Use the `for` loop to iterate over a sequence of numbers.