user3483060
user3483060

Reputation: 407

matrix with values zero or ones

I have the next matrix:

structure(list(`1` = c(0, 0, NA, NA, NA, NA, 0, 0, NA, NA, NA, 
1, NA, NA, NA), `2` = c(1, 0, NA, NA, NA, NA, NA, 0, NA, NA, 
NA, 1, NA, NA, NA), `4` = c(NA, NA, 0, 1, 1, 0, NA, NA, 0, 1, 
1, NA, 1, 0, 0), `5` = c(NA, NA, 0, 1, 1, 0, NA, NA, 1, 1, NA, 
NA, 1, 0, 1), `6` = c(NA, NA, 0, 1, 1, 0, NA, NA, 1, 0, NA, NA, 
1, 0, NA), `7` = c(NA, NA, NA, 1, 1, 0, NA, NA, 0, 1, NA, NA, 
1, 0, NA), `8` = c(NA, NA, NA, 1, 0, 0, NA, NA, 1, 0, NA, NA, 
1, 0, NA)), row.names = c(NA, 15L), class = "data.frame")

I want to create the following matrix based in the previous matrix, I have created the next code but it does not work.

for(i in 1:nrow(mat)){
  for(j in 1:7){
    if(mat[i,j]==0){
      next }else{
    if(mat[i,j]==1){
        mat[i,j:7]<-1
      }else{
        if(is.na(mat[i,j])){
    mat[i,j]<-NA
      }}}
  }
  
}

The idea is for each row for example:

0,0,0,1,0,0,0

The idea is to create a matrix describing an intervention over time. I mean 1 is when the intervention is applied.

I hope you can help me with it.

Upvotes: 1

Views: 46

Answers (2)

jblood94
jblood94

Reputation: 17011

A vectorized function using cummax:

f <- function(m) {
  blnNA <- is.na(m)
  m[blnNA] <- 0
  m <- matrix(cummax(c(t(m + 1:nrow(m)))), nrow(m), ncol(m), 1) - 1:nrow(m)
  m[blnNA] <- NA
  m
}

f(m)
#>       [,1] [,2] [,3] [,4] [,5] [,6] [,7]
#>  [1,]    0    1   NA   NA   NA   NA   NA
#>  [2,]    0    0   NA   NA   NA   NA   NA
#>  [3,]   NA   NA    0    0    0   NA   NA
#>  [4,]   NA   NA    1    1    1    1    1
#>  [5,]   NA   NA    1    1    1    1    1
#>  [6,]   NA   NA    0    0    0    0    0
#>  [7,]    0   NA   NA   NA   NA   NA   NA
#>  [8,]    0    0   NA   NA   NA   NA   NA
#>  [9,]   NA   NA    0    1    1    1    1
#> [10,]   NA   NA    1    1    1    1    1
#> [11,]   NA   NA    1   NA   NA   NA   NA
#> [12,]    1    1   NA   NA   NA   NA   NA
#> [13,]   NA   NA    1    1    1    1    1
#> [14,]   NA   NA    0    0    0    0    0
#> [15,]   NA   NA    0    1   NA   NA   NA

Upvotes: 0

Ma&#235;l
Ma&#235;l

Reputation: 52199

With cummax + apply:

t(apply(mat, 1, \(x) cummax(ifelse(is.na(x), 0, x)) + x*0))

output

    1  2  4  5  6  7  8
1   0  1 NA NA NA NA NA
2   0  0 NA NA NA NA NA
3  NA NA  0  0  0 NA NA
4  NA NA  1  1  1  1  1
5  NA NA  1  1  1  1  1
6  NA NA  0  0  0  0  0
7   0 NA NA NA NA NA NA
8   0  0 NA NA NA NA NA
9  NA NA  0  1  1  1  1
10 NA NA  1  1  1  1  1
11 NA NA  1 NA NA NA NA
12  1  1 NA NA NA NA NA
13 NA NA  1  1  1  1  1
14 NA NA  0  0  0  0  0
15 NA NA  0  1 NA NA NA

Upvotes: 1

Related Questions