Loop in R
We can categories the R loops in mainly three types, implicit
loops, explicit loops and iterators.
R supports implicit loops,
which is called vectorization. This is built-in to many functions and standard
operators few of them are as below :-
§ apply()-When
we have some structured blob of data that we wish to perform operations
§ lapply()-traversing
over a set of data like a list or vector- it will return a list rather than a
vector
§ sapply()-traversing
over a set of data like a list or vector
§ tapply()
§ aggregate()
§ mapply()
applydemo
<- matrix(data=cbind(rnorm(30, 0), rnorm(30, 2), rnorm(30, 5)), nrow=30,
ncol=3)
apply(applydemo,1,mean)
output
[1] 1.940783 3.034701 1.836892 2.420311
1.569139 2.533843 1.784813 1.366241 2.664395 1.452193 2.896668 1.671177
2.550266 1.358662 2.393071 1.301494
[17]
1.903415 2.060350 2.663350 2.913506 1.987428 2.910139 1.941491 1.950160 2.413743
2.102208 1.444518 1.800371 2.497475 1.740320
apply(applydemo,2,mean)
output
[1]
-0.1035741 1.7916236 4.6222626
sapply(5:8,
function(x) x^2)
[1]
25 36 49 64
lapply(5:8,
function(x) x^2)
output
[[1]]
[1]
25
[[2]]
[1]
36
[[3]]
[1]
49
[[4]]
[1]
64
Explicit
Loops
R
provides three ways to write loops:
1. For
2. Repeat
3. While
##For
Loops
demodata<- LETTERS[1:6]
for(item in demodata)
{
print(item);
}
##Repeat
rep(1:3,length.out=7)
repeat
{
g <- rnorm(1)
if
(g > 1.0) break
cat(g,"\n")
}
##While
while
(g < 1)
{
g <- rnorm(1)
cat(g,"\n")
}
Loop Control Statement
·
Break
·
Next
#Break
demodata<- LETTERS[1:6]
for(item in demodata)
{
if(item=="D")
{
break;
}
print(item);
}
#Next
demodata<- LETTERS[1:6]
for(item in demodata)
{
if(item=="D")
{
next;
}
print(item);
}
Iterator
An iterator is a special type
of object that generalizes the notion of a looping variable. When passed as an
argument to a function that knows what to do with it, the iterator supplies a
sequence of values. The iterator also maintains information about its state, in
particular its current index
# Simple
i1 <- iter(1:3)
nextElem(i1)
[1] 1
nextElem(i1)
[1] 2
nextElem(i1)
[1] 3
# vector iterator
i1 <- iter(1:3,
checkFunc=function(i) i %% 2 == 0)
nextElem(i1)
[1] 2
Note
: For Iterator install-> library(iterators)
Loop in R
Reviewed by Rupesh
on
04:41
Rating:
No comments: