set.seed(3)
myvec <- rnorm(1000)
output <- vector("list", length = length(myvec))
for(i in 1:length(myvec)){
output[[i]] <- floor(myvec[i])^2 + exp(myvec[i])^2/2
}
Suppose I have a pre-specified vector of numbers called myvec. I would like to loop over each element, and the final output is a list.
Using for loop can be very inefficient. Similarly, using lapply is also quite slow.
output <- lapply(1:length(myvec), function(i){
floor(myvec[i])^2 + exp(myvec[i])^2/2
})
Is there an alternative that's much faster? The function that I made up above is a toy function. In reality, the function I'm running is much more complicated than just floor(myvec[i])^2 + exp(myvec[i])^2/2, so I'm looking for alternatives to for loop and lapply.