Using apply
- Applies a function to the rows or columns of a dataframe/matrix
apply(X, MARGIN, FUN)Xis the dataMARGINis whether we're doing rows or columns (1or2)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 a10 x 1output, the mean for each rowapply(d1, 2, mean)will return a1 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 dataMARGINis whether we're doing rows or columns (1or2)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 a10 x 1output, the mean for each rowapply(d1, 2, mean)will return a1 x 5output, the mean for each column