JGCRI / programing-resources

Repo for JGCRI software training resources
1 stars 0 forks source link

A few notes #7

Open ashiklom opened 5 years ago

ashiklom commented 5 years ago

Just a few comments, while they're fresh on my mind after this tutorial was run. At some point, I can open a PR with the revisions indicated here.

n <- 2500
data <- matrix(rnorm(n^2), n, n)

loop <- function(x) {
  # Create a blank object, but don't pre-allocate
  result <- numeric()
  for (col in seq_len(ncol(x))) {
    result <- c(result, mean(x[, col]))
  }
  result
}

loop2 <- function(x) {
  # Pre-allocate memory
  result <- numeric(n)
  for (col in seq_len(ncol(x))) {
    result[col] <- mean(x[, col])
  }
  result
}

microbenchmark::microbenchmark(
  loop = loop(data),
  loop2 = loop2(data),
  apply = apply(data, 2, mean),
  colMeans = colMeans(data)
)
#> Unit: milliseconds
#>      expr       min        lq      mean    median        uq       max
#>      loop 40.100811 43.093317 46.842495 46.797980 47.979631  91.96781
#>     loop2 33.794390 35.292669 38.227707 36.128164 37.599016  78.73944
#>     apply 53.358353 77.231662 79.053773 78.281253 80.420645 161.34888
#>  colMeans  4.413732  4.550543  5.251516  4.653667  4.807175  17.61293
#>  neval
#>    100
#>    100
#>    100
#>    100
f <- function(x) {
  if (!is.numeric(x)) {
    warning("X must be numeric")
    result <- NA
  } else {
    a <- x + 3
    b <- x^2 + 2
    result <- x + a + b
  }
  result
}

...may be better written with an early return, like this:

f <- function(x) {
  if (!is.numeric(x)) {
    warning("X must be numeric")
    return(NA)
  }
  a <- x + 3
  b <- x^2 + 2
  x + a + b
}
bpbond commented 5 years ago

Some thoughts re the loops section:

I really liked @pralitp 's framing of "know and use language-specific powers/features" or something like that. So, loops in R aren't always bad, but be darn sure you know about the *apply functions; you don't need to template/polymorph everything but if writing in C++ be aware of their power and pitfalls. Et cetera. Anyway, I do like that as an alternative and more positive way to frame that section.