[R] Using functions/loops for repetitive commands

Shekhar shekhar2581 at gmail.com
Thu May 5 13:41:45 CEST 2011


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)
lapply(seq_along(x),function(i) {//your logic})

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



More information about the R-help mailing list