我有一个随机值的矩阵:
set.seed(1)
n_rows <- 6
n_cols <- 5
mat_random <- matrix(runif(n = 30,0.04,0.06),n_rows,n_cols)
[,1] [,2] [,3] [,4] [,5]
[1,] 0.04531017 0.05889351 0.05374046 0.04760070 0.04534441
[2,] 0.04744248 0.05321596 0.04768207 0.05554890 0.04772228
[3,] 0.05145707 0.05258228 0.05539683 0.05869410 0.04026781
[4,] 0.05816416 0.04123573 0.04995398 0.04424285 0.04764776
[5,] 0.04403364 0.04411949 0.05435237 0.05303348 0.05739382
[6,] 0.05796779 0.04353114 0.05983812 0.04251110 0.04680698
除了最后一列0.05:
之外,每个列都有一个上限capped_value <- 0.05
我想创建另一个矩阵,它会逐行限制值并累计超出值直到最后一列。以下是for:
的示例mat_new <- mat_random
for(rw in 1:n_rows){
for(cl in 1:n_cols){
if(cl!=n_cols){
mat_new[rw,cl+1] <- mat_new[rw,cl+1]+ifelse(mat_new[rw,cl]>capped_value,mat_new[rw,cl]-capped_value,0)
mat_new[rw,cl] <- ifelse(mat_new[rw,cl]>capped_value,capped_value,mat_new[rw,cl])
}
}
}
[1,] 0.04531017 0.05000000 0.05000000 0.05000000 0.05557908
[2,] 0.04744248 0.05000000 0.05000000 0.05000000 0.05416922
[3,] 0.05000000 0.05000000 0.05000000 0.05000000 0.05839809
[4,] 0.05000000 0.04939988 0.04995398 0.04424285 0.04764776
[5,] 0.04403364 0.04411949 0.05000000 0.05000000 0.06477966
[6,] 0.05000000 0.05000000 0.05000000 0.05000000 0.05065513
是否有可能以某种有效的方式做到这一点?
我非常感谢你的帮助。
答案 0 :(得分:0)
我们可以删除其中一个循环以提高效率
m1 <- mat_random
for(j in head(seq_len(ncol(m1)), -1)) {
m1[, j + 1] <- m1[, j + 1] <- m1[, j + 1] + ((m1[,j] -
capped_value) * (m1[,j] > capped_value))
m1[, j][m1[,j] > capped_value] <- capped_value
}
identical(m1, mat_new)
#[1] TRUE