我怎样才能知道一个矩阵有多少行满足一个相当复杂的标准(在R中)?
作为一个例子,这里有一种方法可以获得滚动4(公平)骰子的所有可能结果的矩阵我怎样才能知道一个矩阵有多少行满足一个相当复杂的标准(在R中)?,r,indexing,statistics,matrix,probability,R,Indexing,Statistics,Matrix,Probability,作为一个例子,这里有一种方法可以获得滚动4(公平)骰子的所有可能结果的矩阵 z这对我很有用: 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
z这对我很有用:
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))
require(合并)
#返回单个组合的所有可能子集的总和
酷!比我的干净多了!我不知道%in%函数,它会派上用场的。。。我不知道combn可以把一个函数作为一个参数:D
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))
sum(apply(z, 1, function(x) 5 %in% unlist(sapply(1:4, function(i) combn(x, i, sum)))))