I have two dataframes in wide format. Each of the columns is a time series of page hits for various wikipedia articles. 

```
set.seed(123)
library(tidyr)

time = as.Date('2009-01-01') + 0:9

wiki_1 <- 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 <- 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)
)

```

I want to combine one of the columns from the first dataset (`wiki_1`) with n columns from the second dataset (`wiki_2`). But this selection should be based on how close the median values of the columns in `wiki_2` are to those in `wiki_1` e.g. by order of magnitude. 

In this example, for n = 2, Y should be matched with C and D because of how close their median values are. 

```
median(wiki_1$Y) # 7
median(wiki_2$C) # 6
median(wiki_2$D) # 4.5

```

I'm not sure how to implement the difference in median values criterion to get the desired result.

Additionally, it would be useful to be able to randomly sample from the columns in `wiki_2` that satisfy the criterion as my real dataset has many more columns.

This is what I'm working with so far: 

```
df <- zoo(cbind(subset(wiki_1,select="Y"), 
                   subset(wiki_2,select=c("C","D"))),time)

```