Re: [R] Factor function

From: Petr Savicky <savicky_at_praha1.ff.cuni.cz>
Date: Tue, 26 Apr 2011 18:52:30 +0200

On Tue, Apr 26, 2011 at 10:51:33AM +0200, Petr PIKAL wrote:
> Hi
>
>
> d<-data.frame(matrix(c("ww","ww","xx","yy","ww","yy","xx","yy","NA"),
> ncol=3, byrow=TRUE))
>
> Change character value "NA" to missing value <NA>
> d[d[,3]=="NA",3]<-NA
>
> If you want drop any unused levels of a factor just use
>
> factor(d[,3])
> [1] xx yy <NA>
> Levels: xx yy

An explicit NA is a good idea. If the NA is introduced before creating the data frame, then also the data frame will not contain the unwanted level.

  a<-matrix(c("ww","ww","xx","yy","ww","yy","xx","yy","NA"),   ncol=3, byrow=TRUE)
  a[a[,3]=="NA",3]<-NA
  d<-data.frame(a)
  d[,3]

  [1] xx yy <NA>
  Levels: xx yy

If the replacement should be done in the whole matrix, then

  a[a=="NA"]<-NA

may be used.

Petr Savicky.



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. Received on Tue 26 Apr 2011 - 17:01:35 GMT

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.2.0, at Tue 26 Apr 2011 - 18:30:32 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.

list of date sections of archive