Skip to content

Instantly share code, notes, and snippets.

@joshuaulrich
Created July 10, 2017 18:17
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 joshuaulrich/9b21130999561db4b5fdb14cbfb62aa7 to your computer and use it in GitHub Desktop.
Save joshuaulrich/9b21130999561db4b5fdb14cbfb62aa7 to your computer and use it in GitHub Desktop.
Subsetting showdown: matrix vs xts
library(xts)
library(microbenchmark)
set.seed(21)
m <- matrix(1,5e6,50)
x <- .xts(m,1:nrow(m))
i <- sort(sample(nrow(m),2e4))
j <- sample(50, 10)
I <- i[1]
J <- j[1]
microbenchmark(m[i,], x[i,], unit="us") # faster than matrix for rows
microbenchmark(m[,J], x[,J], unit="us") # faster than matrix for 1 column
microbenchmark(m[,j], x[,j], unit="us") # faster than matrix for columns
microbenchmark(m[i,J], x[i,J], unit="us") # similar for rows and 1 column
microbenchmark(m[i,j], x[i,j], unit="us") # faster for rows and columns
microbenchmark(m[I,J], x[I,J], unit="us") # "terrible" for single-element  
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment