title: How to randomly select and bind data columns based on their median values in R?
body: <p>I have two dataframes in wide format. Each of the columns is a time series of page hits for various wikipedia articles. </p>
  
  <pre><code>set.seed(123)
  library(tidyr)
  
  time = as.Date('2009-01-01') + 0:9
  
  wiki_1 &lt;- data.frame(
    W = sample(1:1000,10,replace = T),
    X = sample(1:100,10,replace = T),
    Y = sample(1:10,10,replace = T),
    Z = sample(1:10,10, replace = T)
  )
  
  wiki_2 &lt;- data.frame(
    A = sample(500:1000,10,replace = T),
    B = sample(90:100,10,replace = T),
    C = sample(1:10,10,replace = T),
    D = sample(1:10,10,replace = T)
  )
  </code></pre>
  
  <p>I want to combine one of the columns from the first dataset (<code>wiki_1</code>) with n  columns from the second dataset (<code>wiki_2</code>). But this selection should be based on how close the median values of the columns in <code>wiki_2</code> are to those in <code>wiki_1</code> e.g. by order of magnitude. </p>
  
  <p>In this example, for n = 2, Y should be matched with C and D because of how close their median values are. </p>
  
  <pre><code>median(wiki_1$Y) # 7
  median(wiki_2$C) # 6
  median(wiki_2$D) # 4.5
  </code></pre>
  
  <p>I'm not sure how to implement the difference in median values criterion to get the desired result.</p>
  
  <p>Additionally, it would be useful to be able to randomly sample from the columns in <code>wiki_2</code> that satisfy the criterion as my real dataset has many more columns.</p>
  
  <p>This is what I'm working with so far: </p>
  
  <pre><code>df &lt;- zoo(cbind(subset(wiki_1,select="Y"), 
                     subset(wiki_2,select=c("C","D"))),time)
  </code></pre>