Using the "as Numeric" function in Rstudio

Asked

Viewed 237 times

1

Hello! I am trying to create a new binary variable to an existing database using the following code:

leaders$warbefore <- as.numeric(leaders$interwarbefore == '1', leaders$civilwarbefore == '1')

"Leaders" is the name of the existing database and "warbefore" is the new variable I created.

When I use the above code, it means that the new variable I created,"warbefore", is equal to 1 if the selected variables, "interwarbefore" and"civilwarbefore", are both equal to 1.

However, I would like the variable "warbefore" to be equal to 1 when "interwarbefore" is equal to 1 OR when "civilwarbefore" is equal to 1.

In the code I am using the requirement is that both variables are equal to 1, but I want when only one of them is equal to 1, "warbefore" also be 1.

Can anyone help me reformulate the code? Thank you

  • 4

    Try using the operator or |, leaders$warbefore <- as.numeric(leaders$interwarbefore == '1' | leaders$civilwarbefore == '1') if it doesn’t work you can try the function ifelse also leaders$warbefore <- ifelse(leaders$interwarbefore == '1' | leaders$civilwarbefore == '1', 1, 0)

  • That’s right, Jorge! Thank you very much, dear!!!

No answers

Browser other questions tagged

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