0
df <- 
 SUB    CONC    
  1     baseline (predose)
  2     screen 
  2     predose

I want to add a flag such that if CONC column has "predose" written in it regardless of other things in the cell, then give it a flag 1, otherwise 0.

   dfout <- 
 SUB    CONC                  PREDOSE  
  1     baseline (predose)     1 
  2     screen                 0
  2     predose                1

How can I do this in R? I used RStudio.

Amer
  • 2,131
  • 3
  • 23
  • 38
  • 2
    Possible duplicate of [How to create a TRUE or FALSE column based on regexpr() findings in R?](https://stackoverflow.com/questions/28269170/how-to-create-a-true-or-false-column-based-on-regexpr-findings-in-r) OR [Add column to data frame which returns 1 if string match a certain pattern](https://stackoverflow.com/questions/24698916/add-column-to-data-frame-which-returns-1-if-string-match-a-certain-pattern/) – Ronak Shah Sep 18 '17 at 03:48

1 Answers1

1

We can use grepl with pattern specified as 'predose' to create a logical vector and then coerce that to binary with as.integer

df$PREDOSE <- as.integer(grepl('predose', df$CONC))
df$PREDOSE
#[1] 1 0 1
akrun
  • 874,273
  • 37
  • 540
  • 662
  • 1
    yep! Thanks a lot! – Amer Sep 18 '17 at 03:46
  • is there a way, for example, to add flag number 2 if the cell has "screen", and 0 if it is not "predose" or "screen"? (i.e. incase if I need to put more than one flag) – Amer Sep 18 '17 at 04:06
  • @Amer In that case, you could create a key value dataset and merge with the original dataset – akrun Sep 18 '17 at 05:45