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