[R] To many NA's from mean(..., na.rm=T) when a column is all NA's

Jim Robison-Cox jimrc at math.montana.edu
Mon Jun 13 19:28:17 CEST 2005


I see.
   So apply() first changes the dataframe to a matrix, which made it
a matrix of text values, then mean made no sense for any column, so I got
all NA's.

Thanks, Peter,

Jim

On 13 Jun 2005, Peter Dalgaard wrote:

> Jim Robison-Cox <jimrc at math.montana.edu> writes:
>
> >  Summary:
> >   If I have a data frame or a matrix where one entire column is NA's,
> > mean(x, na.rm=T) works on that column, returning NaN, but fails using
> > apply, in that apply returns NA for ALL columns.
> >   lapply works fine on the data frame.
> >
> >   If you wonder why I'm building data frames with columns that could be
> > all missing -- they arise as output of a simulation.  The fact that the
> > entire column is missing is informative in itself.
> >
> >
> >   I do wonder if this is a bug.
>
> It isn't...
>
> Cutting a long story short:
>
> > testcase <- data.frame( x = 1:3, y = rep(NA,3))
> > as.matrix(testcase)
>   x   y
> 1 "1" NA
> 2 "2" NA
> 3 "3" NA
> > testcase <- data.frame( x = 1:3, y = as.numeric(rep(NA,3)))
> > as.matrix(testcase)
>   x  y
> 1 1 NA
> 2 2 NA
> 3 3 NA
> > apply(testcase,2,mean,na.rm=T)
>   x   y
>   2 NaN
>
>
>

Jim Robison-Cox               ____________
Department of Math Sciences  |            |       phone: (406)994-5340
2-214 Wilson Hall             \   BZN, MT |       FAX:   (406)994-1789
Montana State University       |  *_______|
Bozeman, MT 59717-2400          \_|      e-mail: jimrc at math.montana.edu




More information about the R-help mailing list