user33125 user33125 - 1 year ago 75
R Question

Combine observations based on the variable ID if at least 5 IDs are combined

Last week I posted the following question . The idea was to make a loop that determined the content of a database by randomly combining observations based on the variable "id".

For instance:

  • dataset 1: combinations of id 1, 2, 3, 4, 5, 6, 7, 8...

  • dataset 2: combinations of id 1, 2, 3

  • dataset 3: combinations of id 2, 3, 4, 5

  • dataset 4: combinations of id 5, 6, 7, 8, 9, 10...

I got a perfect answer to the question:

for(i in 2:max(o$id)){
for(j in 1:ncol(combis)){
sub=o[o$id %in% combis[,j],]
out=sub[1,] # use your function
out$label=paste(combis[,j],collapse ='') #provide an id so you know for which combination this result is
result=rbind(result,out) # paste it to previous output

However, my question now is the following: is there a way to specify that I only want combinations of at least 5 ids combined? The process takes up a lot of computing time and I noticed that small datasets (with les than 5 different ids) give biased results.

Through this link, a sample of the dataset and the full code can be found to reproduce the example. Please be aware that it can take a while to run the entire code, unless there is something specified that I am only interested in combinations of at least 5 ids.

Answer Source

You can start the loop at 5:

for(i in 5:max(o$id)){

This way, there are at least 5 elements in each combination (see ?combn).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download