r - convert only some factors into a different factor -


i'm trying build factor column relates 2 other factor columns different factor levels. here's example data.

set.seed(1234) a<-sample(letters[1:10],50,replace=true) b<-sample(letters[11:20],50,replace=true) df<-data.frame(a,b) df$a<-as.factor(df$a) df$b<-as.factor(df$b) 

the rule want make creates new column, c, bases it's factor level value based on value of column a. if row in column ="f", row in column c equal whatever entry column b. code i'm trying:

dfn<-dim(df)[1] (i in 1:dfn){ df$c[i]<-ifelse(df$a[i]=="f",df$b[i],df$a[i]) } df 

only spits out numbered index of factor level column b , not actual entry. have done wrong?

i think you'll need little finagling of character values. seems it.

w <- df$a == "f"     df$c <- factor(replace(as.character(df$a), w, as.character(df$b)[w])) 

here quick @ new column,

factor(replace(as.character(df$a), w, as.character(df$b)[w])) #  [1] b g g g g c g s g k c j c c c b c d d b c n j # [31] e c d p b h c c j l g d g d p g e c h # levels: b c d e g h j k l n p s 

Comments

Popular posts from this blog

yii2 - Yii 2 Running a Cron in the basic template -

asp.net - 'System.Web.HttpContext' does not contain a definition for 'GetOwinContext' Mystery -

mercurial graft feature, can it copy? -