title: Replacing values in each column independently according to value order in R
body: <p>I have a matrix:</p>
  
  <pre><code>mat &lt;-structure(c(0.35, 0.27, 0.26, 0.28, 0.23, 0.37, 0.28, 0.27, 0.28, 
  + 0.22, 0.34, 0.27, 0.25, 0.25, 0.24, 0.35, 0.27, 0.25,      0.29, 0.27, 
  + 0.66, 0.37, 0.49, 0.46, 0.42, 0.64, 0.4, 0.48, 0.45,   0.42, 0.81, 
  + 0.39, 0.36, 0.37, 0.36, 0.34, 0.34, 0.43, 0.42, 0.34), .Dim = c(5L, 
  + 8L), .Dimnames = list(c("a", "b", "c", "d", "e"), c("f", "g", 
  + "h", "i", "j", "k", "l", "m")))
  
  print(mat)
       f    g    h    i    j    k    l    m
  a 0.35 0.37 0.34 0.35 0.66 0.64 0.81 0.34
  b 0.27 0.28 0.27 0.27 0.37 0.40 0.39 0.34
  c 0.26 0.27 0.25 0.25 0.49 0.48 0.36 0.43
  d 0.28 0.28 0.25 0.29 0.46 0.45 0.37 0.42
  e 0.23 0.22 0.24 0.27 0.42 0.42 0.36 0.34
  </code></pre>
  
  <p>For each column I want the lowest <code>k</code> values to be replaced by 0</p>
  
  <p>To achieve this, I used a for loop and ifelse:</p>
  
  <pre><code>k &lt;- 3
  for (j in 1:ncol(mat)) { mat[,j][tail(order(mat[,j], decreasing = TRUE, na.last = FALSE), ifelse(nrow(mat)&lt;=k, 0, nrow(mat)-k))] &lt;- 0 }
  
  print(mat)
       f    g    h    i    j    k    l    m
  a 0.35 0.37 0.34 0.35 0.66 0.64 0.81 0.34
  b 0.27 0.28 0.27 0.27 0.00 0.00 0.39 0.00
  c 0.00 0.00 0.25 0.00 0.49 0.48 0.00 0.43
  d 0.28 0.28 0.00 0.29 0.46 0.45 0.37 0.42
  e 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00
  </code></pre>
  
  <p>So, it all worked fine but unfortunately the loop is very slow for a large number of columns.</p>
  
  <p>How can I speed up things? 
  <code>apply</code> seems not to be suitable as I want to the whole matrix returned.</p>