-1

I have a dataframe with string values

id str
a  1
b  10
c  0
d  102
e  010

I need to create a flag such that if there is a 0 in the str, the flag is 1 else, the flag is 0

I'm using the following code :

df$flag <-ifelse(grep('0', df$str) == "1", 1, 0)

But this returns less rows than the number of total rows in df.

On inspection i found that

grep('0', df$str[1]) returns int(0)

whereas grep('0', df$str[2]) returns 1

Any idea how I could use this

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
hbabbar
  • 947
  • 4
  • 15
  • 33

2 Answers2

2
#df$flag <- NULL #unneeded. skip it.
df$flag <- ifelse(grepl('0',df$str), 1, 0)

You need grepl instead of grep

addicted
  • 2,901
  • 3
  • 28
  • 49
  • @RonakShah ah you're absolutely right. I am used to initialized another column with NA actually before filling it with ifelse vectorized statement. – addicted Dec 05 '17 at 06:04
  • this is known as `JAVA` hangover – Hardik Gupta Dec 05 '17 at 06:05
  • @Hardikgupta would like to know what is `JAVA hangover`? – addicted Dec 05 '17 at 06:06
  • nothing against the language (I love it) - In Java we need to initialise every variable before its use, unlike R Python. – Hardik Gupta Dec 05 '17 at 06:11
  • @Hardikgupta haha i see. Sometimes for `NA` value, I encountered error when using `ifelse` statement. Actually that's the reason I have a habit of initializing using `NA`. I am not adept in Java at all :) – addicted Dec 05 '17 at 06:14
1

you can use grepl like this

df <- read.table(text = "id str
a  1
b  10
c  0
d  102
e  010", header = T)

df$Flag <- ifelse(grepl(0,df$str), 1, 0)

> df
  id str Flag
1  a   1    0
2  b  10    1
3  c   0    1
4  d 102    1
5  e  10    1
Hardik Gupta
  • 4,700
  • 9
  • 41
  • 83