我有一个名为MyMatrix的矩阵:
a<-c(1,2,0)
b<-c(0,5,0)
c<-c(8,9,2)
d<-c(5,2,0)
MyMatrix<-cbind(a,b,c,d)
a b c d
[1,] 1 0 8 5
[2,] 2 5 9 2
[3,] 0 0 2 0在MyMatrix中,我希望-1来自每个列中的元素,但前提是元素>0。
例如,产生的矩阵可能是:
a b c d
[1,] 0 0 8 5
[2,] 2 4 8 1
[3,] 0 0 2 0我怎样才能做到这一点?
发布于 2022-06-08 12:27:34
试试这个:
safeSample<-function(x) {if (length(x)==1) x else sample(x, 1)}
apply(MyMatrix, 2,
function(x) {
ind<-safeSample(which(x>0))
x[ind]<-x[ind]-1
x
}
)发布于 2022-06-08 12:20:10
更新
根据反馈,我以前误解了目标,但我想下面的apply方法应该有效
apply(
MyMatrix,
2,
function(v) {
k <- which(v > 0)
idx <- sample(seq_along(k), 1)
replace(v, k[idx], v[k[idx]] - 1)
}
)这给
a b c d
[1,] 0 0 6 5
[2,] 1 4 9 1
[3,] 0 0 2 0我们可以这样做,使用sample生成随机索引,如果其条目大于0,则应由1减去。
idx <- cbind(
sample(nrow(MyMatrix), ncol(MyMatrix), TRUE),
1:ncol(MyMatrix)
)
MyMatrix[idx] <- MyMatrix[idx] - (MyMatrix[idx] > 0)https://stackoverflow.com/questions/72545320
复制相似问题