Implicit Loop in R
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
Implicit Loop in R
Reviewed by Rupesh
on
05:00
Rating:
No comments: