[R] Factor function

Petr Savicky savicky at praha1.ff.cuni.cz
Tue Apr 26 18:52:30 CEST 2011


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.



More information about the R-help mailing list