lundi 21 novembre 2016

Creating a new variable in a dataframe based on conditions

I have a data frame in R. For example, the data frame is called X and includes the following columns:

x1 = c(1,0,0,0)
X2 = c(0,0,0,0)
X3 = c(0,0,0,0)
X4 = c(0,0,1,0)

I want to add a condition, that for each of the 4 subjects, if at least one column is 1, then a new variable will be created getting 1. Else, if all are 0's the new variable will be 0.

I tried this:

if (X$X1 == 1 || X$X2 == 1 || X$X3 == 1 || X$X4 == 1 || X$X5 == 1) 
{
  NewVar = 1
}
else { NewVar = 0 }

However I am keep getting an error:

Error: unexpected 'else' in "else" and in my code R studio say: Unexpected token 'else'

Can you please assist me with finding the problem ? Thank you.

Aucun commentaire:

Enregistrer un commentaire