Alex
Alex

Reputation: 65

For Loop in R (print if is not NA)

I have a 3x5 matrix below and I want to print the non-NA values. I was able to get to this point but it doesn't print anything.

    [,1] [,2] [,3] [,4] [,5]
[1,] NA  .93   NA  .14  .23
[2,] .12 .92   NA  .55   NA
[3,] NA  NA   .32  .19  .88

for(i in 1:nrow(a)){
   for(j in 1:ncol(a)){
     if(a[i,j] != "NA"){
        print(a[i,j]
     }
   }
}

I want to be able to print .93,.14,.23...

Upvotes: 1

Views: 519

Answers (2)

akrun
akrun

Reputation: 887991

Instead of "NA", use is.na

for(i in 1:nrow(a)){
   for(j in 1:ncol(a)){
     if(!is.na(a[i,j])){
        print(a[i,j])
     }
   }
}
#[1] 0.93
#[1] 0.14
#[1] 0.23
#[1] 0.12
#[1] 0.92
#[1] 0.55
#[1] 0.32
#[1] 0.19
#[1] 0.88

Or without using a loop

na.omit(c(t(a)))
#[1] 0.93 0.14 0.23 0.12 0.92 0.55 0.32 0.19 0.88

data

a <- structure(c(NA, 0.12, NA, 0.93, 0.92, NA, NA, NA, 0.32, 0.14, 
0.55, 0.19, 0.23, NA, 0.88), .Dim = c(3L, 5L))

Upvotes: 4

Cole
Cole

Reputation: 11255

Another approach without a loop:

a[!is.na(a)]

Upvotes: 4

Related Questions