# Re: [R] Using functions/loops for repetitive commands

From: Shekhar <shekhar2581_at_gmail.com>
Date: Thu, 05 May 2011 04:41:45 -0700 (PDT)

Hi Derek,
You can accomplish your loop jobs by following means:
(a) use for loop
(b) use while loop
(c) use lapply, tapply, or sapply. (i feel "lapply is the elegant
way )

```---------------For Loop-----------------------------
```
"for" loops are pretty simple to use and is almost similar to any other scripting languages you know.( I am referring to Matlab)

(Example 1) lets say you know that you have to run 10 iterations then
you can run it as

for(i in 1:10) print(i)
//it will print the number from 1 to 10

(Example 2) You don't know how many iterations you need to run. Only
thing you have is some vector and you want to do some operation on that vector. You can do something like this:

myVector<-c(20,45,23,45,89)
for(i in seq_along(myVector)) print(myVector[i]

```-------------Using lapply-------------------------
```
In "lapply" you need to provide mainly two things:
(1)First parameter: vectors or some sequence of numbers
(2)Second parameter: A function which could be user defined function
or some other inbuilt function.

lapply will call the function for every number given in the "First parameter of the function)

For example:

x<-c(10,20,20)

if you see the first parameter i have sent seq_along(x). The outcome of seq_along(x) will be 1, 2,3.
Now lapply will take each of these numbers and call the function. That means lapply is calling the function thrice for the current data set something like this

```function(1) { //your logic}
function(2) { }
function(3) { //)

```

That means your logic inside the function will be executed for each and every value specified in the first parameter of the lapply function.

I hope it helps you in some way.

For your problem, i am making a guess that you are using data frame or matrix to store the data and then you want to automate the data right? You can try using "lapply", i think that would be efficient..Let me also try ..

Regards,
Som Shekhar

R-help_at_r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code. Received on Thu 05 May 2011 - 14:51:23 GMT

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.2.0, at Thu 05 May 2011 - 18:00:05 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.