R fill values ​​depending on the combination

I have a list of several (variable) letter numbers in combination, for example:

vec = c("a", "b", "c") comb = unlist(lapply(1:length(vec), combn, x = vec, simplify = FALSE), recursive = FALSE) # this creates all the combinations of the vector I am interested in, ie for three letters: # abc ab ac bc abc 

For each combination, I try to fill the elements, depending on the position, into vectors with the same length as the number of vectors. Therefore, I am trying to get:

 a = 200 b = 020 c = 002 ab = 220 ac = 202 bc = 022 abc = 222 

Now I am trying with loops replacing each element of the i, j array, but since all values ​​are "2", should there be a more efficient way to do this? Thanks!!

+8
arrays loops binary r combinations
source share
3 answers

Starting with vec , you can do ...

 comb_cases = do.call(expand.grid, lapply(vec, function(x) c("", x))) Var1 Var2 Var3 1 2 a 3 b 4 ab 5 c 6 ac 7 bc 8 abc 

There will be an empty string for an empty set, as it probably should be.

From here ...

 comb = do.call(paste0, comb_cases) # [1] "" "a" "b" "ab" "c" "ac" "bc" "abc" do.call(paste0, split( ifelse(nchar(as.matrix(comb_cases)), 2, 0), col(comb_cases)) ) # [1] "000" "200" "020" "220" "002" "202" "022" "222" 

ifelse slow, but it can be fixed later if that matters.

+9
source share

This is essentially a loop, but it might be easier to understand:

 sapply( lapply(comb, match, vec), function(x) paste(replace(numeric(3), x, 2), collapse="")) #[1] "200" "020" "002" "220" "202" "022" "222" 
+6
source share

Here is another option with factor

 sapply(comb, function(x) paste(table(factor(x, levels = vec))*2, collapse="")) #[1] "200" "020" "002" "220" "202" "022" "222" 

We can also use the FUN argument in combn

 unlist(sapply(seq_along(vec), function(x) combn(vec, x, FUN = function(y) paste(table(factor(y, levels= vec))*2, collapse=''))) ) #[1] "200" "020" "002" "220" "202" "022" "222" 

Or in a slightly compact version

 unlist(lapply(seq_along(vec), function(x) combn(vec, x, FUN = function(y) paste((vec %in% y)*2, collapse="")) )) #[1] "200" "020" "002" "220" "202" "022" "222" 
+5
source share

All Articles