Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.