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
- if in the row there is a 1, then all the elements after this 1 should be equals 1.
- if there is an NA then this value should be equals NA
The idea is to create a matrix describing an intervention over time. I mean 1 is when the intervention is applied.
- If I have something like this: 0,NA,NA,1,0,NA,1 I want to get for example: 0,NA,NA,1,1,NA,1
I hope you can help me with it.
CodePudding user response:
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
CodePudding user response:
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