Apply Functions in R

All materials on our website are shared by users. If you have any questions about copyright issues, please report us to resolve them. We are always happy to assist you.
of 9

Please download to get full document.

View again

1. Apply functions<br />The Team<br /> 2. Apply functions<br />Apply functions are used to execute a function repetitively.…
  • 1. Apply functions<br />The Team<br />
  • 2. Apply functions<br />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.<br />
  • 3. Apply family<br />sapply()<br />lapply()<br />apply()<br /><ul><li>mapply()
  • 4. tapply()
  • 5. rapply()</li></li></ul><li>Usage<br />Using Loops!<br />&gt; avg &lt;- numeric (8)<br />&gt; avg<br />[1] 0 0 0 0 0 0 0 0<br />&gt; for(i in 1:8)<br />+ avg[i]&lt;-mean(state.x77[,i])<br />&gt; avg[i]<br />[1] 70735.88<br />&gt; avg<br />[1] 4246.4200 4435.8000 1.1700 70.8786 7.3780<br />[6] 53.1080 104.4600 70735.8800<br />
  • 6. Usage<br />Using ‘apply’<br />&gt; apply (state.x77, 2, median)<br />Population Income Illiteracy Life Exp Murder <br /> 2838.500 4519.000 0.950 70.675 6.850 <br /> HS Grad Frost Area <br /> 53.250 114.500 54277.000<br />The 2 means &quot;go by column&quot; -- a 1 would have meant &quot;go by row.&quot;<br />
  • 7. Usage<br />We construct a function and pass it to apply. It computes the median and maximum of each column of state.x77.<br />
  • 8. Usage<br /> 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<br />
  • 9. lapplyand sapply<br />The lapply() function works on any list. The &quot;l&quot; in &quot;lapply&quot; stands for &quot;list.&quot;<br />The &quot;s&quot; in &quot;sapply&quot; stands for &quot;simplify.&quot;<br />
  • 10. tapply<br />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. <br />&gt;tapply(barley$yield, barley$site, mean) <br />Grand Rapids Duluth University Farm Morris Crookston Waseca <br />24.93167 27.99667 32.66667 35.4 37.42 48.10833<br />
  • Related Search
    We Need Your Support
    Thank you for visiting our website and your interest in our free products and services. We are nonprofit website to share and download documents. To the running of this website, we need your help to support us.

    Thanks to everyone for your continued support.

    No, Thanks