簡體   English   中英

如果列中出現負值,如何復制列?

[英]How can I replicate a column if a negative value occur in the column?

我有以下矩陣(示例):

mat <- matrix(c(seq(8,-1), 
                seq(9,0),
                seq(6,-3)),10,3) 

現在,如果列中出現負值,我想重新啟動該列。 所以我想得到以下矩陣:

solution_mat <- mat 
solution_mat[10,1] <-8 
solution_mat[8:10,3] <- 6:4

感謝幫助!

如果數字嚴格按照您的示例降序排列,則可以將每列的值取模x[1] + 1 ,其中x[1]是列中的第一個值。 這樣做的好處是,如果負數多於正數,它將繼續工作。

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

嘗試以下操作:

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM