Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
x1 = cm[,1]
n <- length(x1)
x1[(x1 != sort(x1,partial=n-1)[n-1]) & (x1 != sort(x1,partial=n-2)[n-2]) & (x1 != sort(x1,partial=n-3)[n-3])] <- 0
@gvegayon

This comment has been minimized.

Copy link

gvegayon commented Jun 3, 2016

Don't know if this helps but you can make it faster this way:

rm(list=ls())
n <- 1e3
x1 = (1:n)[order(runif(n))]

fun1 <- function(x) {
  x[(x != sort(x,partial=n-1)[n-1]) & (x != sort(x,partial=n-2)[n-2]) & (x != sort(x,partial=n-3)[n-3])] <- 0
  x
}


fun2 <- function(x) {
  i <- (n-1):(n-3)
  x[!(x %in% sort(x, partial=i)[i])] <- 0
  x
}

library(microbenchmark)

microbenchmark::microbenchmark(fun1(x1), fun2(x1))

identical(fun1(x1),fun2(x1))

# > microbenchmark::microbenchmark(fun1, fun2)
# Unit: nanoseconds
#  expr min lq   mean median   uq  max neval
#  fun1  45 46 103.41     46 49.5 5499   100
#  fun2  49 53  62.80     53 53.0 1052   100
# 
# > identical(fun1(),fun2())
# [1] TRUE

# Applying it to a matrix -----------------
X <- matrix(runif(100*1000), ncol=100)
microbenchmark(apply(X, 2, fun1), apply(X, 2, fun2))

identical(apply(X, 2, fun1), apply(X, 2, fun2))

# Creating elements

W <- apply(X, 2, fun2)
sapply(1:ncol(W), function(x) assign(paste0("x",x), W[,x], envir = .GlobalEnv))

Makes sense?

@pachamaltese

This comment has been minimized.

Copy link
Owner Author

pachamaltese commented Jun 3, 2016

I never heard of microbenchmark but it is very clear

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.