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)
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 variableb
, one could usegrepl("[bdg]", b, ignore.case = TRUE)
). Ifb
is numeric, you use conditional statements (as you have).Basically you could use
or
or similarly using transform
The confusion is likely that you are trying to figure out
which
of the ifelse statement is 1 or 0. For this you could usewhich