首页 > 解决方案 > R Fastest way to write for loop using vectorization

问题描述

Say I have a simple for loop which adds a random value to a data frame.

person <- c("Clark Kent", "Bruce Wayne", "Tony Stark", "Carol Danvers")
sleep_time <- c(8, 1, 3, 6)
data <- data.frame(person, sleep_time)

for (i in 1:length(data$person)) {
  idle <- sample(20:32, 1)
  data$idle_time[i] <- idle
}

How would I write this using R's vectorization capabilities to speed up the process to the fastest it can be? I know for loops are discouraged, but have also read that the apply functions are not too much faster.

My apologies if this questions is similar to other. I am new to utilizing R's vectorization capabilities and am having some trouble understanding how to convert between loops and the much faster vectorized form.

Please let me know if you need any more information.

Thank you.

标签: rperformancefor-loopvectorizationapply

解决方案


Not sure what actually your use case is however for this particular case you can completely let go off for loop by doing

data$idle_time <- sample(20:32, nrow(data))

You might want to include the condition replace = TRUE if your number of rows is greater than length(20:32).


推荐阅读