How can I find out how many rows of a matrix satisfy a rather complicated criterion (in R)?

岁酱吖の 提交于 2019-12-05 22:00:43
sum(apply(z, 1, function(x) 5 %in% unlist(sapply(1:4, function(i) combn(x, i, sum)))))

This works for me:

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))

And outputs:

[1] "1083 combinations over 1296 have a subset that sums to 5"

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!