并提前感谢您的帮助!
这个问题与我之前发布的问题有关,但我认为它值得单独发布,因为它是一个单独的挑战。
上次我询问了在添加向量后从矩阵中随机选择值的问题。在那个例子中,矩阵和向量都是二进制的。现在我想在添加加权向量后更改加权矩阵中的值。这是一些可以使用的示例代码。
require(gamlss.dist)
mat1<-matrix(c(0,0,0,0,1,0, 0,10,0,0,0,5, 0,0,0,0,1,0, 0,0,3,0,0,0, 0,0,0,0,3,0,
0,0,2,0,0,0, 2,1,0,1,0,1, 0,0,0,0,37,0, 0,0,0,2,0,0, 0,0,0,0,0,1, 1,0,0,0,0,0,
0,1,1,0,0,0), byrow=T, ncol=6, nrow=12)
vec1<-c(0,0,0,1,1,1)
ones <- which(vec1 == 1L)
temp=rZIP(sum(vec1)) #rZIP is a function from gamlss.dist that randomly selects values from a zero-inflated distribution
vec1[ones]<-temp
向量中的值是从零膨胀分布中采样的(感谢这个问题)。当我将向量绑定到矩阵时,我想从同一列中随机选择一个非零值,然后从中减去向量值。如果向量值大于同一列中随机选择的值,我会看到更复杂的情况。在这种情况下,它只会将该值设置为零。
这是早期问题中的一些修改后的代码,这些代码不适用于此问题,但可能会有所帮助。
foo <- function(mat, vec) {
nr <- nrow(mat)
nc <- ncol(mat)
cols <- which(vec != 0) #select matrix columns where the vector is not zero
rows <- sapply(seq_along(cols),
function(x, mat, cols) {
ones <- which(mat[,cols[x]] != 0)
out <- if(length(ones) != 0) {
ones
} else {
sample(ones, 1)
}
out
}, mat = mat, cols = cols)
ind <- (nr*(cols-1)) + rows #this line doesn't work b/c it is not binary
mat[ind] <- 0 #here is where I would like to subtract the vector value
mat <- rbind(mat, vec)
rownames(mat) <- NULL
mat
}
有任何想法吗?再次感谢所有出色的帮助!
编辑:
感谢下面 bnaul 的帮助,我离答案更近了,但我们遇到了上次遇到的同样问题。示例函数在只有一个非零值的列上无法正常工作。我已经使用 Gavin Simpson 的 if else 语句解决了这个问题(这是前一个案例中的解决方案)。我已经调整了矩阵,使其列只有一个非零值。
mat1<-matrix(c(0,0,0,0,1,0, 0,0,0,0,0,5, 0,0,0,0,1,0, 0,0,0,0,0,0, 0,0,0,0,3,0,
0,0,2,0,0,0, 2,1,0,1,0,1, 0,0,0,0,37,0, 0,0,0,2,0,0, 0,0,0,0,0,1, 1,0,0,0,0,0,
0,0,0,0,0,0), byrow=T, ncol=6, nrow=12)
vec1<-c(0,1,0,0,1,1)
ones <- which(vec1 == 1L)
temp=rZIP(sum(vec1))
vec1[ones]<-temp
mat2 = rbind(mat1, vec1)
apply(mat2, 2, function(col) { #Returns matrix of integers indicating their column
#number in matrix-like object
nonzero = which(head(col,-1) != 0); #negative integer means all but last # of elements in x
sample_ind = if(length(nonzero) == 1){
nonzero
} else{
sample(nonzero, 1)
}
; #sample nonzero elements one time
col[sample_ind] = max(0, col[sample_ind] - tail(col,1)); #take max of either 0 or selected value minus Inv
return(col)
}
)
再次感谢!