Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to deal with grep failure returning integer(0) in R?

Tags:

r

return-value

In the grep expression,when the value of grep is integer(0),print "ok",how can i do?

> data="haha"
> grep("w",data)
integer(0)
> if (grep("w",data)==0) print ("ok")
Error in if (grep("w", data) == 0) print("ok") : 
  argument is of length zero
like image 264
Ff Yy Avatar asked Sep 22 '12 00:09

Ff Yy


People also ask

How to use grepl R function?

The grepl R function searches for matches of certain character pattern in a vector of character strings and returns a logical vector indicating which elements of the vector contained a match. Example how to use grepl: As we can see, grepl () returns a logical vector for each element.

Does grep-Q return 0 when it fails?

(though beware it will also run the second grep and/or echo if the first echo fails) Edit 1 > explain grep -q ... Sure. In normal situations, grep return status is 0 (and just returns "not 0" if an error occurs (eg. file not found))

How to grep return status is 0?

In normal situations, grep return status is 0 (and just returns "not 0" if an error occurs (eg. file not found)) grep -qF exp file "returns" 0 if it finds exp in file, error otherwise ( grep -q exp file would do that if the exp regexp was matched in file ). Show activity on this post.

What does integer(0) mean when using the which() function in R?

Sometimes when you use the which () function in R, you may end up with integer (0) as a result, which indicates that none of the elements in a vector evaluated to TRUE. For example, suppose we use the following code to check which elements in a vector are equal to the value 10:


1 Answers

You can use either length or identical

R> if (length(grep("w", data)) == 0) print ("ok")
[1] "ok"

R> if (identical(grep("w", data), integer(0))) print ("ok")
[1] "ok"

You could also use grepl instead of grep

R> if (!any(grepl("w", data))) print('ok')
[1] "ok"
like image 172
GSee Avatar answered Sep 22 '22 09:09

GSee