Like this presentation? Why not share!

# R: Apply Functions

## on Jan 22, 2010

• 13,634 views

R: Apply Functions

R: Apply Functions

### Views

Total Views
13,634
Views on SlideShare
13,581
Embed Views
53

Likes
0
0
0

### Report content

• Comment goes here.
Are you sure you want to

## R: Apply FunctionsPresentation Transcript

• Apply functions
The Dataminingtools.net Team
• Apply functions
Apply functions are used to execute a function repetitively. &quot;Apply&quot; functions keeps us from having to write loops to perform some operation on every row or every column of a matrix or data frame, or on every element in a list.
• Apply family
sapply()
lapply()
apply()
• mapply()
• tapply()
• rapply()
• Usage
Using Loops!
&gt; avg &lt;- numeric (8)
&gt; avg
[1] 0 0 0 0 0 0 0 0
&gt; for(i in 1:8)
+ avg[i]&lt;-mean(state.x77[,i])
&gt; avg[i]
[1] 70735.88
&gt; avg
[1] 4246.4200 4435.8000 1.1700 70.8786 7.3780
[6] 53.1080 104.4600 70735.8800
• Usage
Using ‘apply’
&gt; apply (state.x77, 2, median)
Population Income Illiteracy Life Exp Murder
2838.500 4519.000 0.950 70.675 6.850
53.250 114.500 54277.000
The 2 means &quot;go by column&quot; -- a 1 would have meant &quot;go by row.&quot;
• Usage
We construct a function and pass it to apply. It computes the median and maximum of each column of state.x77.
• Usage
apply() works on each row, one at a time, to find the smallest number in each row. which() function, returns the indices within a vector for which the vector holds the value TRUE
• lapplyand sapply
The lapply() function works on any list. The &quot;l&quot; in &quot;lapply&quot; stands for &quot;list.&quot;
The &quot;s&quot; in &quot;sapply&quot; stands for &quot;simplify.&quot;
• tapply
tapply() is a very powerful function that lets us break a vector into pieces and apply some function to each of the pieces. It is like sapply(), except that with sapply() the pieces are always elements of a list. With tapply() we get to specify how the breakdown is done.
&gt;tapply(barley\$yield, barley\$site, mean)
Grand Rapids Duluth University Farm Morris Crookston Waseca
24.93167 27.99667 32.66667 35.4 37.42 48.10833