[R] what is returned if a match is not found using grep

Duncan Murdoch murdoch at stats.uwo.ca
Tue Aug 11 17:04:13 CEST 2009


Rnewbie wrote:
> sorry, I still have a question. What is the difference between an empty
> vector and a vector of length 0?
>
> When I assign
> x<-c()
> is.null(x) is TRUE
>
> x<-integer(0)
> is.null(x) is FALSE
>   

NULL is a special object in R.  is.null() returns TRUE for it.  c() 
returns it. 

integer(0) is not a special object.  It's a vector of type integer that 
has no elements.  You can get other types of length zero vectors:  
list(), numeric(0), etc.  (The 0 is optional in integer(0) and 
numeric(0), but I find it makes the code clearer.)

The type of an empty vector is important when you combine it with 
another one.  For example,

c(1, integer(0))

gives a numeric vector, but

c(1, character(0))

converts the whole thing to character.

Duncan Murdoch
>
> Duncan Murdoch-2 wrote:
>   
>> Rnewbie wrote:
>>     
>>> dear all,
>>>
>>> I tried to use grep to match IDs in two dataframes
>>>
>>> grep(DF1$ID[i], DF2$ID)
>>>
>>> I wanted to use condition in a loop, but I have the problem to define
>>> what
>>> is in return if a match is not found. I used mode() and class() to
>>> compare
>>> between the attributes when a match is found and not found, but the mode
>>> and
>>> class are the same in both cases, numeric and integer, respectively.
>>>
>>> When a match is not found, grep returns "integer(0)". Is.numeric() and
>>> Is.integer() of the return gave TRUE but arithmetic calculation is not
>>> possible.
>>>   
>>>       
>> See the Value section of the ?grep man page.  By default, R returns a 
>> vector of indices of entries in x that match the pattern.  Since you 
>> have no matches, you get a vector of length 0.  That is printed as 
>> integer(0).  (This is also the function call that would create a vector 
>> of length 0.)
>>
>> One simple test for no results is  length(grep(...)) == 0.
>>
>> Duncan Murdoch
>>     
>>> For example,
>>> If a match is not found for i=12,
>>>
>>> grep(DF1$ID[12], DF2$ID) returns "integer(0)" and 
>>>
>>> grep(DF1$ID[12], DF2$ID)+10 returns "numeric(0)"
>>>
>>> I will appreciate any suggestions. Thanks in advance.
>>>
>>>
>>>
>>>       
>> ______________________________________________
>> R-help at r-project.org mailing list
>> https://stat.ethz.ch/mailman/listinfo/r-help
>> PLEASE do read the posting guide
>> http://www.R-project.org/posting-guide.html
>> and provide commented, minimal, self-contained, reproducible code.
>>
>>
>>     
>
>




More information about the R-help mailing list