[R] ifelse() question

F Z gerifalte28 at hotmail.com
Fri Oct 29 01:48:54 CEST 2004


Hi

I have a data.frame with dim = 18638 (rows)     6 (cols)

names(dat)
[1] "id"      "long"    "lat"     "species" "type"    "size"

Variable "species" and "type" are factors.  Species has 5 levels "BOV" "CAP" 
"CER" "OVI" "POR"
Variable "type" has 11 levels "BRD" "CL" ... "OTHER"

I would like to replace the values on species by the values on types only if 
species is == "POR"
I tried:

x<-ifelse(dat$species %in% "POR",dat$type,dat$species)
dat[,4]<-x
but levels(x)
[1] "1"  "2"  "3"  "4"  "5"  "6"  "8"  "9"  "10" "11" "12"

So x changes the factor names by numbers.  I can not use factor() to recover 
the names since the resulting factors in x are a mixture of factors from 
species and type.

I also tried

x<-gsub(pattern = "POR",replacement= factor(dat$type),dat$species)  with 
same behavior.

Apparently I did not have my granola bar today so I can't find a solution!  
Any help is greatly appreciated

Thanks!

Francisco




More information about the R-help mailing list