Re: [R] Factor function

From: Petr Savicky <>
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)

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

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


may be used.

Petr Savicky. mailing list PLEASE do read the posting guide 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 Please read the posting guide before posting to the list.

list of date sections of archive