On Fri, 2007-10-12 at 18:47 +0800, Samuel wrote: > Hi, > > I'm quite fresh to R, and a layman of English as well. I hope I can make you > understood. > > Now I have two vectors A and B. Is there any quick way to know whether B is > a subset of A? and If B is a subset of A, can I know easily which elements > in A (the index of A) equals to B's elements accordingly? > > For example, > > > a<-1:20 > > b=c(2,5,9,7,4,8,3) > > > > Question 1: we know b is a subset of a, but how does R know that? > > Question 2: since we know b is a subset of a, then which a's elements equals > to b? I do it like this: > > test=0 > > for (i in 1:length(b)) test[i]=which(a==b[i]) > > test > > > > Is there any easier way to know these indexes? > > Thanks a lot for you helps in advance
You can use %in% to determine whether or not the elements of 'b' are in 'a': a <- 1:20 b <- c(2, 5, 9, 7, 4, 8, 3) > b %in% a [1] TRUE TRUE TRUE TRUE TRUE TRUE TRUE To get the indices of b's elements in 'a', you can do: > which(a %in% b) [1] 2 3 4 5 7 8 9 If you want to know whether or not ALL of the elements of 'b' are in 'a', you add the use of all() to the first example: > all(b %in% a) [1] TRUE See ?"%in%" and ?all HTH, Marc Schwartz ______________________________________________ R-help@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.