How to create a factor variable from other factors?

Asked

Viewed 125 times

2

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

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

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

I tried to use the function ifelse, but it seems to me that it applies to var. numeric only.

1 answer

3


After creating the X variable, use the command as.factor() in that 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)
  • Thank you, Rafael. It was going wrong, because I inserted only one = instead of ==

  • 1

    in R a = is the same as <- for the equality test, you have to use ==

Browser other questions tagged

You are not signed in. Login or sign up in order to post.