[R] ifelse() question

Peter Alspach PAlspach at hortresearch.co.nz
Fri Oct 29 02:33:54 CEST 2004


Francisco

Did you try changing the factors to character, with as.character?

Also you don't really need ifelse() for this.  Something like the
following (untested) should do it:

dat[,4] <- as.character(dat[,4])
dat[,5] <- as.character(dat[,5])
dat[dat[,4]=='POR',4] <- dat[dat[,4]=='POR',5]
dat[,4] <- as.factor(dat[,4])
dat[,5] <- as.factor(dat[,5])


Peter Alspach

>>> "F Z" <gerifalte28 at hotmail.com> 29/10/04 12:48:54 >>>
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

______________________________________________
R-help at stat.math.ethz.ch mailing list
https://stat.ethz.ch/mailman/listinfo/r-help 
PLEASE do read the posting guide!
http://www.R-project.org/posting-guide.html

______________________________________________________

The contents of this e-mail are privileged and/or confidenti...{{dropped}}




More information about the R-help mailing list