How to use grepl with a character vector length greater than one?

457 views Asked by At

Trying to create a conditional dummy variable (c) which converts b >= x to c = 1 and b < x to c = 0.

An example output when x = 3:

a b c
1 1 0
2 3 1
3 4 1
4 2 0
df$c<-ifelse(grepl(b[b <= 3], df$b), as.numeric(1), as.numeric(0))

I've tried using the above ifelse() function, but grepl allows for a character of only length 1:

In grepl(b[b <= 3],df$b) : (argument 'pattern' has length > 1 and only the first element will be used)

1

There are 1 answers

0
Oliver On

I think your a bit confused with grepl and how (and when) regular expressions are used. Regular expressions are used to find patterns in strings (such as figuring wheter "b", "d", or "g" a part of variable b, one could use grepl("[bdg]", b, ignore.case = TRUE)). If b is numeric, you use conditional statements (as you have).

Basically you could use

df$c <- with(df, ifelse(b <= 3, 1, 0)) 

or

df$c <- ifelse(df$b <= 3, 1, 0)

or similarly using transform

df <- transform(df, c = ifelse(b<=3, 1, 0))

The confusion is likely that you are trying to figure out which of the ifelse statement is 1 or 0. For this you could use which

df$c <- 0
df$c[which(b <= 3)] <- 1