gpt4 book ai didi

r - 从 R 中的加权矩阵中的随机值中减去

转载 作者:行者123 更新时间:2023-12-04 09:37:49 25 4
gpt4 key购买 nike

并提前感谢您的帮助!

这个问题与我发布的一个有关 before ,但我认为它应该有自己的帖子,因为它是一个单独的挑战。

上次我询问了在添加向量后从矩阵中随机选择值的问题。在那个例子中,矩阵和向量都是二进制的。现在我想在添加加权向量后更改加权矩阵中的值。这是一些可以使用的示例代码。

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

向量中的值是从零膨胀分布中采样的(感谢 this question)。当我将向量绑定(bind)到矩阵时,我想从同一列中随机选择一个非零值,然后从中减去向量值。如果向量值大于同一列中随机选择的值,我会看到更复杂的情况。在这种情况下,它只会将该值设置为零。

这是来自早期问题的一些修改后的代码,这些代码不适用于此问题,但可能会有所帮助。
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)
}
)

再次感谢!

最佳答案

mat2 = rbind(mat1, vec1)    
apply(mat2, 2, function(col) {
nonzero = which(head(col,-1) != 0);
sample_ind = sample(nonzero, 1);
col[sample_ind] = max(0, col[sample_ind] - tail(col,1));
return(col)
}
)

我做了一些简化;希望它们不会与您的想法相冲突。首先,我忽略了只对向量的非零元素进行操作的要求,因为从任何东西中减去 0 都不会改变它。其次,我绑定(bind)矩阵和向量,然后对结果按列执行操作,因为这比在两个单独的数据结构中跟踪索引然后将它们组合起来要容易一些。

关于r - 从 R 中的加权矩阵中的随机值中减去,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7036133/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com