Posts

Showing posts with the label apply function

Learn to Code in R: for Loops and tapply, lapply, and sapply.

Image
Continuing on with the discussion of for loops and apply functions bring us to another set of apply functions used to, well, apply a function to data in different ways. In this post, I will be: Discussing the arrays or data arrangements for which the different apply functions are designed. That is, when to use each one. Comparing for loops to tapply, lapply, and sapply. I will write for loops for each so you can better familiarize yourself with for loops and situations where you can use the apply functions, instead. The data I will be using for this is the same data set that I used for the apply function post . This is some code I used to prepare the data to get it to its current state. Some of which I will be discussing later. I mostly provide this for the sake of disclosure and clarity. lapply and sapply: Apply a function over a Vector or List This is the most apparent and obvious replacement to a for loop. You give lapply the information set that you wish to iterat...

Learn to Code in R: For Loops, and Apply Function.

Image
When analyzing data you often have to iterate through a set of values, or apply the same function to to that set. While R does not have a great reputation for iterative processes, the apply functions are a way around writing a slow for loop. Mastering the use of the apply functions will make your coding much more efficient and versatile. In this post, I will discuss the following: for loops. When and how to use them. I'll also briefly mention while loops. How to use apply . I will address  tapply ,  lapply , and  sapply in a subsequent post. To help demonstrate how the apply function can be used instead of a for loop, I will carry out the same task using both methods. Before I do that, I am going to go over some looping basics for those who may be unfamiliar or may need a review. For Loop Basics A for loop iterates through the elements of a vector (a set of values), where at each iteration will be represented by the object provided in the for statement. ...