【问题标题】:Write a R function to find binary subset编写一个 R 函数来查找二进制子集
【发布时间】:2020-09-02 01:29:04
【问题描述】:

我有一个二进制向量 x=(1,0,0,1)。假设包含此向量自身的低阶项为 (0,0,0,0)、(0,0,0,1)、(1,0,0,0) 和 (1,0,0,1) .我如何在 R 中找到这个低阶向量。

到目前为止我所理解的:基本上我们想要找到子集,将每个 1 替换为 0。但是要在 R 中做到这一点?我一无所知?

这是我到目前为止所尝试的。

a<-c(1,0,0,1)
M<-length(a)

for(i in 1:M){
  
  ifelse(a[i]==1, a[i]<-0, next)
  print(a)
  
  }
[1] 0 0 0 1
[1] 0 0 0 0

我要详细查找的内容:例如,我有 4 个因素 A、B、C、D。这里 (1,0,0,1) 表示 AD。

现在我想要一个 (1,0,0,1) 的子集,这意味着 AD。在我的子集中,我不能有 B 和 C。结果将是二进制形式的 {} {A} {D} {AD} (0,0,0,0), (1,0,0,0),( 0,0,0,1),(1,0,0,1)。

【问题讨论】:

    标签: r


    【解决方案1】:

    这是一种依靠expand.grid 来完成繁重工作的方法:

    vecs = lapply(a, seq, 0)   # keep 0s as 0, make 1s c(1, 0)
    do.call(expand.grid, vecs) # generate all combinations
    #   Var1 Var2 Var3 Var4
    # 1    1    0    0    1
    # 2    0    0    0    1
    # 3    1    0    0    0
    # 4    0    0    0    0
    

    【讨论】:

    • 如何更改输出的列名?
    • 它是一个数据框,所以任何适用于数据框的东西都适用于此。你可以使用names(result) = c('A', 'B', 'C', 'D')setNames(result, ...)colnames(result) = ...等。
    【解决方案2】:

    使用RcppAlgos::permuteGeneral

    library(RcppAlgos)
    A <- t(apply(permuteGeneral(length(a), sum(a)), 1, function(x) {a[x] <- 0; a}))
    A[!duplicated(A), ]
    #      [,1] [,2] [,3] [,4]
    # [1,]    0    0    0    1
    # [2,]    0    0    0    0
    # [3,]    1    0    0    1
    # [4,]    1    0    0    0
    

    【讨论】:

      【解决方案3】:

      我们可以使用whichcombn*apply函数来执行这个操作。由于这是一个循序渐进的操作,因此逐行查看结果可能会有所帮助。

      这里它被包装在一个名为find_binary_subsets的函数中:

      find_binary_subsets <- function(x){
        # where does x equal 1
        x_eq_1 <- which(x == 1)
        # combinations of indexes where x == 1
        l_w_x <- lapply(length(x_eq_1):1, 
                        FUN = function(l) combn(x_eq_1, l))
        # loop over the combinations of indexes where x == 1, replace by 0, return vector
        # apply(., 2) loops over the columns of a matrix, which is what we want
        combs <- lapply(l_w_x, 
                        FUN = function(d) 
                          apply(d, 2, FUN = function(i){x[i] <- 0; x}))  
        # cbind results, then transpose to arrange by row
        t(cbind(do.call("cbind", combs), x))
      }
      
      find_binary_subsets(a)
      
        [,1] [,2] [,3] [,4]
           0    0    0    0
           0    0    0    1
           1    0    0    0
      x    1    0    0    1
      

      【讨论】:

      • 首先,第 2 行和第 3 行是重复的。我的输出中不能有重复的行。在这里,我正在寻找详细信息:例如,我有 4 个因素 A、B、C、D。 (1,0,0,1) 表示 AD。现在我想要一个 (1,0,0,1) 的子集,这意味着 AD。在我的子集中,我不能有 B 和 C。结果将是二进制形式的 {} {A} {D} {AD} (0,0,0,0), (1,0,0,0),( 0,0,0,1),(1,0,0,1)。
      • 编辑了我的答案,改为按行排列。
      猜你喜欢
      • 1970-01-01
      • 2022-12-07
      • 2016-01-25
      • 2022-01-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多