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

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

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"

Instead of grep, youcould use grepl which returns a logical:

> if (grepl("w",data)== FALSE) print ("ok") else print("donkeykong")
[1] "ok"


> if (grepl("h",data)== FALSE) print ("ok") else print("donkeykong")
[1] "donkeykong"

Need Your Help

PHP, in_array and fast searches (by the end) in arrays

php performance search

I have a doubt about what's the better way to make a fast search in arrays (I'm talking about an specific case).

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.