[英]How can I replicate a column if a negative value occur in the column?
I have following matrix (example):我有以下矩阵(示例):
mat <- matrix(c(seq(8,-1),
seq(9,0),
seq(6,-3)),10,3)
Now I would like to restart the column if a negative value occur in the column.现在,如果列中出现负值,我想重新启动该列。 So I would like to get following matrix:
所以我想得到以下矩阵:
solution_mat <- mat
solution_mat[10,1] <-8
solution_mat[8:10,3] <- 6:4
Thanks for help!感谢帮助!
If the numbers are strictly descending series as in your example, you could take the value of each column modulo x[1] + 1
, where x[1]
is the first value in the column.如果数字严格按照您的示例降序排列,则可以将每列的值取模
x[1] + 1
,其中x[1]
是列中的第一个值。 This has the advantage that it will continue to work if there are more negative numbers than positive ones.这样做的好处是,如果负数多于正数,它将继续工作。
apply(mat, 2, function(x) x %% (x[1] + 1))
#> [,1] [,2] [,3]
#> [1,] 8 9 6
#> [2,] 7 8 5
#> [3,] 6 7 4
#> [4,] 5 6 3
#> [5,] 4 5 2
#> [6,] 3 4 1
#> [7,] 2 3 0
#> [8,] 1 2 6
#> [9,] 0 1 5
#> [10,] 8 0 4
Try the following:尝试以下操作:
apply(mat, 2, function(x){
inx <- which(x < 0)
x[inx] <- x[seq_along(inx)]
x
})
# [,1] [,2] [,3]
# [1,] 8 9 6
# [2,] 7 8 5
# [3,] 6 7 4
# [4,] 5 6 3
# [5,] 4 5 2
# [6,] 3 4 1
# [7,] 2 3 0
# [8,] 1 2 6
# [9,] 0 1 5
#[10,] 8 0 4
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.