代码之家  ›  专栏  ›  技术社区  ›  Brani

我怎样才能找出一个矩阵有多少行满足一个相当复杂的标准(在R中)?

  •  3
  • Brani  · 技术社区  · 16 年前

    作为一个例子,这里有一种方法可以得到一个矩阵,其中包含了掷4个(公平)骰子的所有可能结果。

    z <- as.matrix(expand.grid(c(1:6),c(1:6),c(1:6),c(1:6)))
    

    你可能已经明白了,我正在努力解决这个问题 a question that was closed 不过,在我看来,这是个挑战。我用计数技术来解决这个问题(我的意思是用手),最后我得到了很多结果,子集的和是5,等于1296个问题中的1083个。这个结果和问题结束前给出的答案是一致的。我想知道如何使用R生成结果的子集(比如z1,其中dim(z1)=[1083,4])。你有什么想法吗?

    非常感谢。

    2 回复  |  直到 9 年前
        1
  •  4
  •   Jonathan Chang    16 年前
    sum(apply(z, 1, function(x) 5 %in% unlist(sapply(1:4, function(i) combn(x, i, sum)))))
    
        2
  •  1
  •   nico    16 年前

    这对我很有用:

    require(combinat)
    
    # Returns the sums of all the possible subsets for a single combination
    comb <- function(values)
        {
        sums <- NULL
    
        # Sum each combination of 1,2,... n-1 dice
        for (i in 1:(length(values)-1))
            {
            c <- combn(values, i)
            sums <- c(sums, colSums(c))
            }
    
        # Also sum all the dice
        sums <- c(sums, sum(values))
    
        comb <- sums
        }
    
    # Returns TRUE if the array contains a certain value
    hasVal <- function(values, n)
        {
        hasVal <- (length(which(values == n)) > 0)
        }
    
    dice <- as.matrix(expand.grid(1:6, 1:6, 1:6, 1:6))
    theSum <- 5
    
    # Get the sums of all the subsets for each line
    sums <- apply(z, 1, comb)
    # See which columns of sums contain 5 
    has5 <- apply(sums, 2, hasVal, theSum)
    # Now count them :)
    print(paste(length(which(has5 == TRUE)), " combinations over ", 
            length(has5), " have a subset that sums to ", theSum))
    

    和输出:

    [1] “超过1296的1083个组合有一个和为5的子集”