Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

argument 'pattern' has length > 1 and only the first element will be used numeric grepl

Tags:

r

I keep getting this warning using grepl with a factor variable in an ifelse statement: "argument 'pattern' has length > 1 and only the first element will be used"

I have these variables: x7 and y7. x7 is a character variable that’s mutually exclusive, y7 is a factor variable that is not mutually exclusive and thus a string of numbers (0 thru 9).

x7 can end with any letter, but I want to limit to being equal to Z or J. If it’s equal to Z, I want y7 to end with any of these values in the string (0, 1, 2, 3, 4).

Here’s what I wrote:

test = ifelse( ( x7 %in% c( "Z" ) & grepl( c( 0 , 1 , 2 , 3 , 4 ) , y7 ) ) | x7 %in% c( "J" ) , 1 , 0 ) 

So, creating a dummy variable (test) if x7 is Z and y7 is 0:4 OR if x7 is J, it’s 1. All others will be 0.

I keep getting this warning: "argument 'pattern' has length > 1 and only the first element will be used" meaning, only the 0 is being considered in z7 rather than 0:4.

So, if it’s “123” or “246”, it won’t count them because it doesn’t start with 0. But it does count if it’s “014” or “056”. I need it to count all sequences that include any of the numbers 0 through 4, not just the ones that start with 0.

If any of these values (0 , 1 , 2 , 3 , 4) are in the string, a dummy will be created equalling 1.

like image 462
kendalorgera Avatar asked Dec 17 '25 19:12

kendalorgera


1 Answers

In grepl:

grepl(c(0, 1, 2, 3, 4) , c(1, 2))

The first argument pattern should be of length 1, in your case it is of length 5. To match digits from 0 to 4 you can do:

grepl("[0-4]", c("0", "4", "5", "9"))
# [1]  TRUE  TRUE FALSE FALSE
like image 184
Jozef Avatar answered Dec 19 '25 10:12

Jozef



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!