[R] the quick way to report the invalid value

Peter Dalgaard p.dalgaard at biostat.ku.dk
Fri Jun 24 09:27:04 CEST 2005


Gabor Grothendieck <ggrothendieck at gmail.com> writes:

> On 6/23/05, ronggui <0034058 at fudan.edu.cn> wrote:
> > for example,in my data d,the value 1:9,NA is valid and the others are invalid.
> > and i want to report something like:
> > the variable z has invalid value.
> > 
> > is there any function to do so?
> > 
> > i though this will work but fails:
> > 
> > > d
> >    x  y  z
> > 1   1 NA  1
> > 2   2  2  2
> > 3   3  3  3
> > 4   4  4  4
> > 5   5  5  5
> > 6   6  6  6
> > 7   7  7  7
> > 8   8  8  8
> > 9   9  9  9
> > 10 NA 10  9
> > 
> > >myfun<-function(x) {
> > if(any(a<-match(x,NA,nomatch=0)>0))
> > cat(deparse(substitute(x)),"has invalid value","\n")}
> > >apply(d,2,FUN=myfun)
> > newX[, i] has invalid value
> > newX[, i] has invalid value
> 
> Try looping over the names of d:
> 
> junk <- lapply(names(d), function(n) cat(n, d[,n], "\n"))

or something along the lines of which(sapply(d,myfun)) where myfun
returns logical. This works only if d is a data frame (not matrix),
but you can also use apply(...,2,..) as in
 
> which(apply(is.na(airquality),2,any))
  Ozone Solar.R
      1       2
> which(sapply(airquality, function(x) any(is.na(x)) ))
  Ozone Solar.R
      1       2

If you want the names as a character vector, names(which(...)) gets
you there, or you can do

> z <- apply(is.na(airquality),2,any)
> names(z)[z]
[1] "Ozone"   "Solar.R"
 

-- 
   O__  ---- Peter Dalgaard             Øster Farimagsgade 5, Entr.B
  c/ /'_ --- Dept. of Biostatistics     PO Box 2099, 1014 Cph. K
 (*) \(*) -- University of Copenhagen   Denmark          Ph: (+45) 35327918
~~~~~~~~~~ - (p.dalgaard at biostat.ku.dk)                  FAX: (+45) 35327907




More information about the R-help mailing list