0

I'd like to create a conditional new_column from 2 existing columns. Existing columns must contain either 0 or 1. I had some ideas about loops already which are not working.

In a nutshell, if column1 has a number equal to 1 and column2 has a number equal to 0, then new_column will be 0 and only equal to 1 if both columns are 1).

desired output

Column1  column2  new_column
  1        0         0
  0        0         0
  1        1         1

I am a newbie to R.

I have already tried several topics such as:

I want to thanks the R community for their help

Peter
  • 11,500
  • 5
  • 21
  • 31
J. Perez
  • 117
  • 1
  • 2
  • 7
  • 1
    Welcome to StackOverflow! Please read the info about [how to ask a good question](http://stackoverflow.com/help/how-to-ask) and how to give a [reproducible example](http://stackoverflow.com/questions/5963269) . This will make it much easier for others to help you. – Jaap Jul 17 '17 at 10:03

2 Answers2

1

And what about if column2 is 1 and column1 is 0? Should column3 also be 0? If that is the case you can simply just do:

df$column3 <- df$column1*df$column2

In this case, if one (or both) of the two columns is 0, the third one also be 0 and if both are 1, the third one will be 1.

Lukas Heeren
  • 149
  • 1
  • 10
  • what if I want to create the 3rd column on different conditions: now, the first column has to be one and the second 0 for the 3rd one to be 1 and 0 in any other case. – J. Perez Jul 17 '17 at 10:23
  • 2
    Then just do: ifelse(column1 == 1 & column2 == 0, 1, 0) – Lukas Heeren Jul 17 '17 at 10:37
1

You might also want to look beyond 0 or 1 where multiplying may not be perfectly suitable the try this;

df$col3 <- 0 
df$col3[df$col1 == 1 & df$col2 ==1] <- 1
linkonabe
  • 661
  • 7
  • 23