Assume we have the following permutations of the letters, "a", "b", and "c":
library(combinat)
do.call(rbind, permn(letters[1:3]))
# [,1] [,2] [,3]
# [1,] "a""b""c"
# [2,] "a""c""b"
# [3,] "c""a""b"
# [4,] "c""b""a"
# [5,] "b""c""a"
# [6,] "b""a""c"
Is it possible to perform some function on a given permutation "on-the-fly" (i.e., a particular row) without storing the result?
That is, if the row == "a""c""b"
or row == "b""c""a"
, do not store the result. The desired result in this case would be:
# [,1] [,2] [,3]
# [1,] "a""b""c"
# [2,] "c""a""b"
# [3,] "c""b""a"
# [4,] "b""a""c"
I know I can apply a function to all the permutations on the fly within combinat::permn
with the fun
argument such as:
permn(letters[1:3], fun = function(x) {
res <- paste0(x, collapse = "")
if (res == "acb" | res == "bca") {
return(NA)
} else {
return(res)
}
})
But this stills stores an NA
and the returned list has 6 elements instead of the desired 4 elements:
# [[1]]
# [1] "abc"
#
# [[2]]
# [1] NA
#
# [[3]]
# [1] "cab"
#
# [[4]]
# [1] "cba"
#
# [[5]]
# [1] NA
#
# [[6]]
# [1] "bac"
Note, I am not interested in subsequently removing the NA
values; I am specifically interested in not appending to the result list "on-the-fly" for a given permutation.