[R] how to test if a vector contain a value?

Barry Rowlingson b.rowlingson at lancaster.ac.uk
Mon Aug 16 15:16:10 CEST 2010


On Mon, Aug 16, 2010 at 2:06 PM, Hyunchul Kim
<hyunchul.kim.sfc at gmail.com> wrote:
> Hi all,
>
> How to convert following simple python script to R
>
>
> if x in a_list:
>    print x
>
> OR
>
> simply, how to test if a vector contain a value?

 if(any(a_list == x)){
  print(x)
 }

Or use %in%:

> a_list=c(1,2,3,4)
> b_list=c(1,2,4)
> 3 %in% a_list
[1] TRUE
> 3 %in% b_list
[1] FALSE


 Or use "match" if you want to know where in a_list it is.

 Any simple beginners guide to R should tell you about these.

Barry



More information about the R-help mailing list