r - 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.
解决方案
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)
.
推荐阅读
- c - 错误:“需要左值作为赋值的左操作数”
- c - 初始化由 int 和 char 指针组成的结构结构成员?
- python - XDG_RUNTIME_DIR 指向不存在的路径
- c# - C# UnitTest 异步方法错误 - System.MissingMethodException:找不到方法:
- django - 不允许的方法:/(Django-Post 方法)
- ruby - 嵌套循环 Ruby 答案
- php - 在 textarea wordpress 中渲染帖子内容?
- reactjs - 如何将属性值从函数传递到 React 中的“模态”对话框?
- mysql - MySQL INET_ATON 更新期间出错,消息是“字符串值不正确”
- java - Deeplearning4j 错误:java.library.path 中没有 jniopenblas