How to create a factor variable from other factors?

2

I would like to create a nominal variable X (factor) in my data.frame from two other already-existing nominal variables Renda and Escolaridade :

Renda    Escolaridade    X 
baixa    fund. incomp    Sim
inter    superior        Nao
alta     pos grad        Nao
alta     medio           Nao

Thus, when Renda = "baixa" and Escolaridade = "fund. incomp" a var. X will receive label= "Sim" and all other combinations will receive label="Nao"

I tried to use the ifelse function, but it seems to apply to var. numeric only.

    
asked by anonymous 16.05.2017 / 13:00

1 answer

3

After creating the variable X, use the command as.factor() in this variable.

df <- data.frame(
   Renda = c("baixa","inter","alta","alta"),
   Escolaridade = c("fund. incomp","superior","pos grad","medio"))
df$X <- ifelse((df$Renda == "baixa" & df$Escolaridade == "fund. incomp"),"Sim","Não")
df$X <- as.factor(df$X)
    
16.05.2017 / 14:37