[英]Subtracting from random values in a weighted matrix in R
並提前感謝您的幫助!
這個問題與我之前發布的問題有關,但我認為它值得單獨發布,因為它是一個單獨的挑戰。
上次我詢問了在添加向量后從矩陣中隨機選擇值的問題。 在那個例子中,矩陣和向量都是二進制的。 現在我想在添加加權向量后更改加權矩陣中的值。 這是一些可以使用的示例代碼。
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
向量中的值是從零膨脹分布中采樣的(感謝這個問題)。 當我將向量綁定到矩陣時,我想從同一列隨機 select 一個非零值,並從中減去向量值。 如果向量值大於同一列中隨機選擇的值,我會看到更復雜的情況。 在這種情況下,它只會將該值設置為零。
這是早期問題中的一些修改后的代碼,這些代碼不適用於此問題,但可能會有所幫助。
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 的幫助,我離答案更近了,但我們遇到了上次遇到的同樣問題。 示例 function 在只有一個非零值的列上無法正常工作。 我已經使用 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 都不會改變它。 其次,我綁定矩陣和向量,然后對結果按列執行操作,因為這比在兩個單獨的數據結構中跟蹤索引然后將它們組合起來要容易一些。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.