简体   繁体   English

R 中的 For 循环(如果不是 NA,则打印)

[英]For Loop in R (print if is not NA)

I have a 3x5 matrix below and I want to print the non-NA values.我在下面有一个 3x5 矩阵,我想打印非 NA 值。 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...我希望能够打印.93,.14,.23...

Instead of "NA" , use is.na代替"NA" ,使用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))

Another approach without a loop:另一种没有循环的方法:

a[!is.na(a)]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM