如何对排列“进行中"进行检查.而不将结果存储在R中 [英] How to perform a check on a permutation "on-the-fly" without storing the result in R
问题描述
假设我们对字母"a","b"和"c"进行以下排列:
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?
也就是说,如果row == "a" "c" "b"
或row == "b" "c" "a"
,则不存储结果.在这种情况下,理想的结果将是:
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"
我知道我可以使用fun
参数将函数应用到combinat::permn
中的所有动态排列中,例如:
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)
}
})
但这仍然存储一个NA
,并且返回的列表包含6个元素,而不是所需的4个元素:
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"
注意,我对随后删除NA
值不感兴趣;我特别感兴趣的是,不对给定的排列即时"添加到结果列表中.
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.
推荐答案
我们可以使用magrittr管道,在该管道中,将输入矩阵绑定到要检查的行,并省略重复的行.
We could use a magrittr pipeline where we rbind the input matrix to the Rows to be checked and omit the duplicate rows.
library(combinat)
library(magrittr)
Rows <- rbind(c("a", "c", "b"), c("b", "c", "a"))
do.call(rbind, permn(letters[1:3])) %>%
subset(tail(!duplicated(rbind(Rows, .)), -nrow(Rows)))
给予:
[,1] [,2] [,3]
[1,] "a" "b" "c"
[2,] "c" "a" "b"
[3,] "c" "b" "a"
[4,] "b" "a" "c"
这篇关于如何对排列“进行中"进行检查.而不将结果存储在R中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!