如何动态检查排列而不将结果存储在R中

问题描述 投票:1回答:2

假设我们对字母“ a”,“ b”和“ 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" 

是否可以在给定的“即时”排列(即特定行)上执行某些功能而不存储结果?

即,如果row == "a" "c" "b"row == "b" "c" "a",则不存储结果。在这种情况下,期望的结果将是:

#      [,1] [,2] [,3]
# [1,] "a"  "b"  "c" 
# [2,] "c"  "a"  "b" 
# [3,] "c"  "b"  "a" 
# [4,] "b"  "a"  "c" 

我知道我可以使用combinat::permn参数将函数应用于fun中的所有动态排列,例如:

permn(letters[1:3], fun = function(x) {
  res <- paste0(x, collapse = "")
  if (res == "acb" | res == "bca") {
    return(NA)
  } else {
    return(res)
  }
})

但是此剧照存储了一个NA,并且返回的列表包含6个元素,而不是所需的4个元素:

# [[1]]
# [1] "abc"
# 
# [[2]]
# [1] NA
# 
# [[3]]
# [1] "cab"
# 
# [[4]]
# [1] "cba"
# 
# [[5]]
# [1] NA
# 
# [[6]]
# [1] "bac"

注意,我对随后删除NA值不感兴趣;我特别感兴趣的是,对于给定的排列,不要“即时”将结果列表添加到结果中。

r permutation permute
2个回答
0
投票
我们可以使用magrittr管道,在该管道中,将输入矩阵绑定到要检查的行,并省略重复的行。

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"


0
投票
对于要忽略的特定条件,您可以return NULL,并且rbind结果将忽略NULL元素并仅绑定所需的组合。

do.call(rbind, combinat::permn(letters[1:3], function(x) if(!all(x == c("a", "c", "b") | x == c("b", "c", "a"))) return(x) )) # [,1] [,2] [,3] #[1,] "a" "b" "c" #[2,] "c" "a" "b" #[3,] "c" "b" "a" #[4,] "b" "a" "c"

类似地,

do.call(rbind, permn(letters[1:3],function(x) { res <- paste0(x, collapse = "") if (!res %in% c("acb","bca")) return(res) })) # [,1] #[1,] "abc" #[2,] "cab" #[3,] "cba" #[4,] "bac"

© www.soinside.com 2019 - 2024. All rights reserved.