0

I am new to R and I am having some issues with manipulating my dataset. I need to create a new column in my dataset based on the conditions of two other columns.

I have a column "is_3t_mine" which takes a value 0 or 1 & another column "is_gold_mine" which takes the value of 0 or 1.

I need a third column "dfa_mine" that meets the conditions;

if is_3t_mine == 0 & is_gold_mine == 0 then "dfa_mine" = 0 all other iterations "dfa_mine" = 1

I've been trying to accomplish this with the pipeline function of dplyr but haven't had any success.

  • Does this answer your question? [R Create new variable based on group and multiple column condition](https://stackoverflow.com/questions/65163562/r-create-new-variable-based-on-group-and-multiple-column-condition) – Michael Roswell Jun 14 '21 at 18:45
  • Welcome to Stack Overflow! I've just flagged your question as a duplicate (here's one place I think it's been asked and answered before) https://stackoverflow.com/q/65163562/8400969. If you feel your question is unique, please be sure to demonstrate research by explaining how it is different from other questions, and include example data and as much info as you can about what you've already tried. Generally, it sounds like you might want something like `df %>% mutate(dfa_mine = as.numeric(sum(is_3t_mine, gold_mine)>0))` – Michael Roswell Jun 14 '21 at 18:48

2 Answers2

2

We can use

df1$dfa_mine <- with(df1, +(!(is_3_mine == 0 & is_gold_mine == 0)))
akrun
  • 874,273
  • 37
  • 540
  • 662
1

Here are 4 ways to accomplish specifically what you are trying to do.

  1. Simplest

    df1$dfa_mine1 <- 1- as.numeric(df1$is_3t_mine == 0 & df1$is_gold_mine == 0)
    
  2. Uses opposite condition. But it is more straightforward.

     df1$dfa_mine2 <- as.numeric(df1$is_3t_mine == 1 | df1$is_gold_mine == 1)
    
  3. Use the property that zero is an absorbing element for multiplication

     df1$dfa_mine3 <- 1- ((1-df1$is_3t_mine)%%2) * ((1-df1$is_gold_mine)%%2)
    
  4. rewriting akrun's answer with the $ sign.

     df1$dfa_mine4 <- with(df1, +(!(df1$is_3t_mine == 0 & df1$is_gold_mine == 0)))
    
niyibizi
  • 26
  • 2