Search code examples
rcombn

Get all combinations for a dynamic length of elements to select


I have a data frame:

dat <- data.frame(toys = c("bear", "car", "plane", "truck", "doll"),
                  price = c(1.23, 2.34, 3.45, 4.56, 5.67))

I now want to get all combinations of toys where I would select 2, 3 and 4 toys at a time.

I could manually just call the combn function three times, e.g.

combn(dat$toys, 2)
combn(dat$toys, 3)
combn(dat$toys, 4)

However, I'm looking for a dynamic solution where I could ideally provide a range (e.g. c(2,4)) and as a result I would get all of the above-mentioned combinations in one call. In my real-life example I would have ~22 toys and want to get a different range of combinations (e.g. all "7 to 14 element" combinations or "8 to 13" etc.).

Any ideas?


Solution

  • use any of

    Map(combn, list(dat$toys),2:4)
    

    or

    lapply(2:4,combn,x = dat$toys)
    

    of course you can add the simplify=FALSE