I am going to invite you to exhibit my original version. I would say that the original loop you wrote is a little easier to read and understand (also probably easier to write) than the other suggested solutions.
Also, the loop is almost as fast as the other solutions: (I borrowed the @Josh O'Brien time code before he removed it from my post.)
set.seed(444)
n = 1e7
sortMe <- matrix(rnorm(2 * n), ncol=2)
sortBy <- matrix(c(sample(n), sample(n)), ncol=2)
system.time({
sorted_JD <- sortMe
for (i in 1:ncol(sortMe)) {
sorted_JD[, i] <- sortMe[, i][sortBy[, i]]
}
})
system.time({
sorted_Jul2 <- sortMe
sorted_Jul2[] <- sortMe[as.vector(sortBy) +
rep(0:(ncol(sortMe) - 1) * nrow(sortMe), each = nrow(sortMe))]
})
system.time({
sorted_Jos <- sortMe
sorted_Jos[] <- sortMe[cbind(as.vector(sortBy), as.vector(col(sortBy)))]
})
system.time({
sorted_Just = matrix(unlist(lapply(1:2,
function(n) sortMe[,n][sortBy[,n]])), ncol=2)
})
all.equal(sorted_JD, sorted_Jul2)
all.equal(sorted_JD, sorted_Jos)
all.equal(sorted_JD, sorted_Just)
source
share