Is the “*apply” family really not vectorized?

前端 未结 4 1742
萌比男神i
萌比男神i 2020-11-22 05:25

So we are used to say to every R new user that \"apply isn\'t vectorized, check out the Patrick Burns R Inferno Circle 4\" which says (I quote):

<
4条回答
  •  长情又很酷
    2020-11-22 06:09

    To me, vectorisation is primarily about making your code easier to write and easier to understand.

    The goal of a vectorised function is to eliminate the book-keeping associated with a for loop. For example, instead of:

    means <- numeric(length(mtcars))
    for (i in seq_along(mtcars)) {
      means[i] <- mean(mtcars[[i]])
    }
    sds <- numeric(length(mtcars))
    for (i in seq_along(mtcars)) {
      sds[i] <- sd(mtcars[[i]])
    }
    

    You can write:

    means <- vapply(mtcars, mean, numeric(1))
    sds   <- vapply(mtcars, sd, numeric(1))
    

    That makes it easier to see what's the same (the input data) and what's different (the function you're applying).

    A secondary advantage of vectorisation is that the for-loop is often written in C, rather than in R. This has substantial performance benefits, but I don't think it's the key property of vectorisation. Vectorisation is fundamentally about saving your brain, not saving the computer work.

提交回复
热议问题