Using apply
- Applies a function to the rows or columns of a dataframe/matrix
- apply(X, MARGIN, FUN)
- Xis the data
- MARGINis whether we're doing rows or columns (- 1or- 2)
- FUNis the function
If you're anything like me, you will never get MARGIN correct on the first try. Simply trying both is fine, but a useful way to think about it:
If we have a 10 x 5 dataframe d1, (10 rows with 5 columns), MARGIN controls which dimension stays the same:
- apply(d1, 1, mean)will return a- 10 x 1output, the mean for each row
- apply(d1, 2, mean)will return a- 1 x 5output, the mean for each column
Using apply
- Applies a function to the rows or columns of a dataframe/matrix
- apply(X, MARGIN, FUN)
- Xis the data
- MARGINis whether we're doing rows or columns (- 1or- 2)
- FUNis the function
If you're anything like me, you will never get MARGIN correct on the first try. Simply trying both is fine, but a useful way to think about it:
If we have a 10 x 5 dataframe d1, (10 rows with 5 columns), MARGIN controls which dimension stays the same:
- apply(d1, 1, mean)will return a- 10 x 1output, the mean for each row
- apply(d1, 2, mean)will return a- 1 x 5output, the mean for each column
 Lab 3: Barplots, Fisher's Exact Test, and For-Loop Review
Lab 3: Barplots, Fisher's Exact Test, and For-Loop Review