[R] Getting all possible combinations

peter dalgaard pdalgd at gmail.com
Thu Aug 24 11:58:39 CEST 2017


> On 24 Aug 2017, at 01:25 , Duncan Murdoch <murdoch.duncan at gmail.com> wrote:
> 
> On 23/08/2017 6:25 PM, Bert Gunter wrote:
>> Doesn't sort by size of subgroup. I interpret the phrase I asterisked as:
> 
> You were fooled by Peter's tricky single negative.
> 

<giggles>... 

Let's do this more carefully, then:

M <- as.matrix(do.call(expand.grid, rep(list(0:1),5)))
M
# This is just 0:31 encoded as (little-endian) binary
apply(M, 1, function(i) sum((2^(0:4))[i]))

# now, use rows of M for logical indexing into "A"-"E"
mode(M) <- "logical"
(l <- apply(M,1,function(i)LETTERS[1:5][i]))

# Clearly not sorted by group size:
#[[1]]
#character(0)
#
#[[2]]
#[1] "A"
#
#[[3]]
#[1] "B"
#
#[[4]]
#[1] "A" "B"
#
#[[5]]
#[1] "C"

# requires this to sort:

o <- order(sapply(l, length))
l[o]





-- 
Peter Dalgaard, Professor,
Center for Statistics, Copenhagen Business School
Solbjerg Plads 3, 2000 Frederiksberg, Denmark
Phone: (+45)38153501
Office: A 4.23
Email: pd.mes at cbs.dk  Priv: PDalgd at gmail.com



More information about the R-help mailing list