Shuguang Sun
2008-Nov-04 15:29 UTC
[R] How to generate a new factor variable by two other factor variables
How to generate a new factor variable by two other factor variables?
For example, if I have two factor variables, factorA and factorB,
factorA factorB
0 0
0 0
1 0
0 1
1 1
Is there a simple way to generate a new 4-levels factor variable as
factorC factorA factorB
0 0 0
0 0 0
1 1 0
2 0 1
3 1 1
--
Shuguang Sun
Fudan University, China
Jorge Ivan Velez
2008-Nov-04 16:10 UTC
[R] How to generate a new factor variable by two other factor variables
Dear Shuguang,
Here are two ways. Perhaps they are not efficient enough, but the work:
# Data
mydata=read.table(textConnection("
factorA factorB
0 0
0 0
1 0
0 1
1 1"),header=TRUE)
closeAllConnections()
# Option 1
mydata$factorC=as.factor(
apply(mydata,1,function(x){
paste(x,sep="",collapse="")
}
))
levels(mydata$factorC)<-list("0"="00",
"1"="10",
"2"="01","3"="11")
mydata
# Option 2
# You'll need to read the data again to see how this option works
mydata$factorC<-apply(mydata,1,function(x){
ifelse(sum(x)==0,0,
ifelse(x[1]==1 & x[2]==0,1,
ifelse(x[1]==0 & x[2]==1,2,3)))
}
)
mydata
HTH,
Jorge
On Tue, Nov 4, 2008 at 10:29 AM, Shuguang Sun <shuguang@gmail.com> wrote:
> How to generate a new factor variable by two other factor variables?
>
> For example, if I have two factor variables, factorA and factorB,
> factorA factorB
> 0 0
> 0 0
> 1 0
> 0 1
> 1 1
>
> Is there a simple way to generate a new 4-levels factor variable as
>
> factorC factorA factorB
> 0 0 0
> 0 0 0
> 1 1 0
> 2 0 1
> 3 1 1
>
> --
> Shuguang Sun
> Fudan University, China
>
> ______________________________________________
> R-help@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.
>
[[alternative HTML version deleted]]