简体   繁体   中英

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. 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM