# For loops (and how to avoid them)

[This article was first published on

Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

My experience when starting out in R was trying to clean and recode data using **R for Public Health**, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

*for()*loops, usually with a few

*if()*statements in the loop as well, and finding the whole thing complicated and frustrating.

In this post, I’ll go over how you can avoid

*for()*loops for both improving the quality and speed of your programming, as well as your sanity.

So here we have our classic dataset called mydata.Rdata

*(you can download this if you want, link at the right):*

And if I were in Stata and wanted to create an age group variable, I could just do:

gen Agegroup=1

replace Agegroup=2 if Age>10 & Age<20

replace Agegroup=3 if Age>=20

But when I try this in R, it fails:

Why does it fail? It fails because Age is a

*vector*so the condition if(mydata$Age<10) is asking “is the vector Age less than 10”, which is not what we want to know. We want to ask, row by row is each element of Age<10, so we need to specify the element of the vector we're referring to. We don't specify the element and thus we get the warning (really, error), "only the first element will be used." So when this fails, the first way people try to solve this problem is with a crazy

*for()*loop like this:

###########Unnecessarily long and ugly code below#######

mydata$Agegroup1<-0

for (i in 1:10){

if(mydata$Age[i]>10 & mydata$Age[i]<20){

mydata$Agegroup1[i]<-1

}

if(mydata$Age[i]>=20){

mydata$Agegroup1[i]<-2

}

}

Here we tell R to go down the rows from i=1 to i=10, and for each of those rows indexed by i, check to see what value of Age it is, and then assign Agegroup a value of 1 or 2.

**This works, but at a high cost**– you can easily make a mistake with all those indexed vectors, and also

**, which would be a big deal if this dataset were 10000 observations instead of 10.**

*for()*loops take a lot of computing timeSo how can we avoid doing this?

One of the most useful functions I have found is one that I have referred to a number of times in my blog so far – the ifelse() function. The ifelse() function evaluates a condition, and then assigns a value if it’s true and a value if it’s false. The great part about it is that it can read in a vector and check each element of the vector one by one so

**you don’t need indices or a loop**. You don’t even need to initialize some new variable before you run the statement. Like this:

mydata$newvariable<-ifelse(Condition of some variable,

Value of new variable if condition is true,

Value of new variable if condition is false)

so for example:

mydata$Old<-ifelse(mydata$Age>40,1,0)

This says, check to see if the elements of the vector mydata$Age are greater than 40: if an element is greater than 40, it assigns the value of 1 to mydata$Old, and if it’s not greater than 40, it assigns the value of 0 to mydata$Old.

But we wanted to assign values 0, 1, and 2 to an Agegroup variable. To do this, we can use

**nested ifelse() statements**:

mydata$Agegroup2<-ifelse(mydata$Age>10 & mydata$Age<20,1,

ifelse(mydata$Age>20, 2,0))

Now this says, first check whether each element of the Age vector is >10 and <20. If it is, assign 1 to Agegroup2. If it's not, then evaluate the next

*ifelse()*statement, whether Age>20. If it is, assign Agegroup2 a value of 2. If it’s not any of those, then assign it 0. We can see that both the loop and the*ifelse()*statements give us the same result:*ifelse()*statement as much as you like.

**Just be careful about your final category**– it assigns the last value to whatever values are left over that didn’t meet any condition (including if a value is NA!) so make sure you want that to happen.

__Other examples of ways to use the__

*ifelse()*function:- If you want to
**add a column with the mean of Weight by sex for each individual,**you can do this with*ifelse()*like this:

mydata$meanweight.bysex<-ifelse(mydata$Sex==0,

mean(mydata$Weight[mydata$Sex==0], na.rm=TRUE),

mean(mydata$Weight[mydata$Sex==1], na.rm=TRUE))

- If you want to
**recode missing values**:

9999,

mydata$Height)

- If you want to
**combine two variables together into a new one**, such as to create a new ID variable based on year (which I added to this dataframe) and ID:

mydata$ID.long<-ifelse(mydata$ID<10,

paste(mydata$year, “-0″,mydata$ID,sep=””),

paste(mydata$year, “-“, mydata$ID, sep=””))

__Other ways to avoid the for loop:__

**The apply functions**: If you think you have to use a loop because you have to apply some sort of function to each observation in your data, think again! Use the*apply()*functions instead. For example:- If you have a lot of missing values and want to recode them all at once, or want to sum up the number of times you see a certain value in a row, check out my post on the apply function here.

- You can also
**use other functions**such as*cut()*to do the age grouping above. Here’s the post on how this function works, so I won’t go over it again, except to say if you convert from a factor to a numeric, *always* convert to a character before converting it to numeric:

Basically,

**any time you think you have to do a loop, think about how you can do it with another function**. It will save you a lot of time and mistakes in your code.

To

**leave a comment**for the author, please follow the link and comment on their blog:**R for Public Health**.R-bloggers.com offers

**daily e-mail updates**about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.

Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.