Skip to content

Instantly share code, notes, and snippets.

@mschubert
Created October 9, 2016 20:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mschubert/3eeb5b35ed52ab21f138f0d799b15316 to your computer and use it in GitHub Desktop.
Save mschubert/3eeb5b35ed52ab21f138f0d799b15316 to your computer and use it in GitHub Desktop.
n = 1:1e7
# use a loop
new_n = rep(NA, length(n))
for (i in seq_along(n))
new_n[i] = n[i] * 2 - 5
# use *apply
new_n = sapply(n, function(x) x * 2 - 5)
# use vector operations
new_n = n * 2 - 5
@mschubert
Copy link
Author

mschubert commented Oct 9, 2016

point out here:

  • seq_along & reserve memory before loop
  • for loops emphasize the object
  • vectorization: even creating helper vectors/matrices speeds things up

and

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment