Note that there are some explanatory texts on larger screens.

plurals
  1. POGrouping functions (tapply, by, aggregate) and the *apply family
    primarykey
    data
    text
    <p>Whenever I want to do something "map"py in R, I usually try to use a function in the <code>apply</code> family. </p> <p>However, I've never quite understood the differences between them -- how {<code>sapply</code>, <code>lapply</code>, etc.} apply the function to the input/grouped input, what the output will look like, or even what the input can be -- so I often just go through them all until I get what I want.</p> <p>Can someone explain how to use which one when?</p> <p>My current (probably incorrect/incomplete) understanding is...</p> <ol> <li><p><code>sapply(vec, f)</code>: input is a vector. output is a vector/matrix, where element <code>i</code> is <code>f(vec[i])</code>, giving you a matrix if <code>f</code> has a multi-element output</p></li> <li><p><code>lapply(vec, f)</code>: same as <code>sapply</code>, but output is a list?</p></li> <li><code>apply(matrix, 1/2, f)</code>: input is a matrix. output is a vector, where element <code>i</code> is f(row/col i of the matrix)</li> <li><code>tapply(vector, grouping, f)</code>: output is a matrix/array, where an element in the matrix/array is the value of <code>f</code> at a grouping <code>g</code> of the vector, and <code>g</code> gets pushed to the row/col names</li> <li><code>by(dataframe, grouping, f)</code>: let <code>g</code> be a grouping. apply <code>f</code> to each column of the group/dataframe. pretty print the grouping and the value of <code>f</code> at each column.</li> <li><code>aggregate(matrix, grouping, f)</code>: similar to <code>by</code>, but instead of pretty printing the output, aggregate sticks everything into a dataframe.</li> </ol> <p>Side question: I still haven't learned plyr or reshape -- would <code>plyr</code> or <code>reshape</code> replace all of these entirely?</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload