Column means with apply in R
Column means with apply, the family that replaces most loops in base R.
column_means <- function(df) {
numeric_cols <- sapply(df, is.numeric)
sapply(df[, numeric_cols, drop = FALSE], mean, na.rm = TRUE)
}
Keywords and builtins used here
functionsapply
The run, in numbers
- Lines
- 4
- Characters to type
- 132
- Tokens
- 34
- Three-star pace
- 90 tpm
At the three-star pace of 90 tokens a minute, this run takes about 23 seconds.
Step 2 of 5 in Vectorized thinking, step 11 of 20 in Language basics.