[R] prblem with NA

jim holtman jholtman at gmail.com
Tue Jan 6 02:27:59 CET 2009


Try vectorizing instead of a loop:

> da <- matrix(nrow=10,ncol=10)
> n <- sample(1:100, 40)
> da[n[1:20]] <- 99
> da[n[21:40]] <- 199
> X <- ifelse(is.na(da), NA, ifelse(da <= 100, 1, 0))
>
>
> X
      [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
 [1,]   NA   NA   NA   NA   NA    1   NA   NA   NA    NA
 [2,]   NA   NA    1    0   NA   NA   NA   NA   NA    NA
 [3,]    1   NA    0    1    1   NA    0    0    1    NA
 [4,]   NA   NA    0   NA    1    1    1    0   NA    NA
 [5,]   NA   NA    0   NA    1    1    1    1   NA    NA
 [6,]   NA   NA    0    0   NA    0   NA   NA    0    NA
 [7,]    1   NA    1   NA   NA   NA   NA    1   NA    NA
 [8,]   NA   NA   NA   NA   NA    0    1    0   NA     1
 [9,]    1   NA   NA    1    0    0    0    0   NA    NA
[10,]   NA    0   NA   NA    0   NA    0   NA   NA    NA
>


On Mon, Jan 5, 2009 at 6:21 PM, kayj <kjaja27 at yahoo.com> wrote:
>
>
> Hi all
>
> I have a data set with the total number of columns =ncol, and the total
> number of rows=nrow. I am trying to loop over the values and id the value is
> less than or equal to 100 to be changed to 1. if the value is greater than
> 100 , to be changed to 0. if NA , let X[i,j]=NA. I ran into a problem where
> if one row in my data set had all values =NA, then the program does not
> continue working past that row!
>
> At some point I get the following error message:
>
> "Error in if (data [i, j] <= 100) { : missing value where TRUE/FALSE needed"
>
> Here is the program
>
> data<-read.table("fileName.txt", header=F, sep='\t')
>
> X=data
> for(i in ncol)
> {
> for(j in nrow)
> {
> if(data[i,j]<=100) {X[i,j]=1}
> if(data[i,j]>100) {X[i,j]=0}
>
> if(is.na(data[i,j])) {X[i,j]=NA}
> }
> }
>
> Thanks
>
> --
> View this message in context: http://www.nabble.com/prblem-with-NA-tp21301527p21301527.html
> Sent from the R help mailing list archive at Nabble.com.
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>



-- 
Jim Holtman
Cincinnati, OH
+1 513 646 9390

What is the problem that you are trying to solve?




More information about the R-help mailing list