If i have a condition, does putting it inside/outside an apply function affect run time significantly for example:
names = c("Joe", "Jen", "Bob")
if("Joe" %in% names){
lapply(1:1000000, function(y){
#Do something computationally intensive
})
}
if("Jen" %in% names){
lapply(1:1000000, function(y){
#Do something computationally intensive
})
}
Versus:
lapply(1:1000000, function(y){
if("Joe" %in% names){
#Do something computationally intensive
}
if("Jen" %in% names){
#Do something computationally intensive
}
})
Thanks
The
ifin the loop is very expensive.Use rbenchmark to see. Writing the first as function ‘a’, the second as ‘b’, gives this:
Suggested to put both “Joe” and “Jen” into names. The results are about the same.
EDIT: Note that the expressions that you give to
benchmarkare evaluated inside the timing loop, and thus function parentheses must be supplied.