[R] length() misbehaving?

Thomas Lumley tlumley at u.washington.edu
Fri Mar 14 18:35:35 CET 2003


On Fri, 14 Mar 2003, David Parkhurst wrote:

> I'm having a weird problem with length(), in R1.6.1 under windows2000.  I have a
> dataframe called byyr, with ten columns, the first of which is named cnd95.
> summary(byyr) shows that byyr$cnd95 contains the factor level "tr" 66 times.  Also,
> when I enter byyr$cnd95 at the command line, I can count 66 "tr" elements in the
> resulting vector.  However, when I enter
>
> n95trt <- length(byyr$cnd95[byyr$cnd95=="tr"])
> n95trt
>

In addition to the sum() approach suggested by other people there's an
approach using %in%

  n95trt <- length(byyr$cnd95[byyr$cnd95 %in% "tr"])

You can check that NA=="tr" returns NA, but NA %in% "tr" returns FALSE.

	-thomas



More information about the R-help mailing list