简体   繁体   中英

R: Loop through matrix, delete cells based on criteria

I am trying to loop through a matrix and change cell values to NA if the cell in the prior column is NA.

Its a big matrix with 9 cols and 57772 rows. Tried different for for loops but I can't seem to get it right.

In short, this Matrix.

m <- structure(c("X","X","X","X","X","X", NA, "X", "X", NA, NA, "X", "X", NA, NA, "X", "X", 
             NA, NA, NA, "X", NA, NA, NA, "X"), .Dim = c(5L, 5L), .Dimnames = list(
               NULL, c("1", "2", "3", "4","5")))

should become this

      1   2   3   4   5  
[1,] "X" "X" NA  NA  NA
[2,] "X" NA  NA  NA  NA 
[3,] "X" "X" "X" NA  NA 
[4,] "X" "X" NA  NA  NA 
[5,] "X" NA  NA  NA  NA 

But with this loop

for(j in ncol(m):2) m[, j] <- ifelse(is.na(m[, j-1]), NA, m[, j])

it only becomes this

      1   2   3   4   5  
[1,] "X" "X" NA  NA  "X"
[2,] "X" NA  NA  "X" NA 
[3,] "X" "X" "X" NA  NA 
[4,] "X" "X" NA  NA  NA 
[5,] "X" NA  NA  NA  NA

A simple loop should suffice here.

for(j in 2:ncol(m) m[, j] <- ifelse(is.na(m[, j-1]), NA, m[, j])

giving:

     1   2   3   4  5 
[1,] "X" "X" NA  NA NA
[2,] "X" NA  NA  NA NA
[3,] "X" "X" "X" NA NA
[4,] "X" "X" NA  NA NA
[5,] "X" NA  NA  NA NA

Note

The input in reproducible form is:

m <- structure(c(NA, NA, "X", NA, NA, NA, NA, "X", NA, NA, NA, NA, 
    NA, NA, NA, NA, NA, NA, NA, "X"), .Dim = c(5L, 4L), .Dimnames = list(
    NULL, c("1", "2", "3", "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