Martin Batholdy
2011-Aug-22 15:51 UTC
[R] test if vector contains elements of another vector (disregarding the position)
Hi, I have the following problem: I have two vectors: i <- c('a','c','g','h','b','d','f','k','l','e','i') j <- c('a', 'b', 'c') now I would like to generate a vector with the length of i that has zeros where i[x] != any element of j and 1 where i[x] == any element of j. So for the example above the vector would look like this: c(1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0) can someone help me on this?
R. Michael Weylandt
2011-Aug-22 15:54 UTC
[R] test if vector contains elements of another vector (disregarding the position)
%in% Here, i %in% j Hope this helps, Michael On Mon, Aug 22, 2011 at 11:51 AM, Martin Batholdy <batholdy@googlemail.com>wrote:> Hi, > > > I have the following problem: > > > I have two vectors: > > i <- c('a','c','g','h','b','d','f','k','l','e','i') > > j <- c('a', 'b', 'c') > > > > now I would like to generate a vector with the length of i that > has zeros where i[x] != any element of j > and 1 where i[x] == any element of j. > > So for the example above the vector would look like this: > > c(1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0) > > > > can someone help me on this? > > ______________________________________________ > 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. >[[alternative HTML version deleted]]
Henrique Dallazuanna
2011-Aug-22 16:35 UTC
[R] test if vector contains elements of another vector (disregarding the position)
Try this: i %in% j * 1 On Mon, Aug 22, 2011 at 12:51 PM, Martin Batholdy <batholdy at googlemail.com> wrote:> Hi, > > > I have the following problem: > > > I have two vectors: > > i <- c('a','c','g','h','b','d','f','k','l','e','i') > > j <- c('a', 'b', 'c') > > > > now I would like to generate a vector with the length of i that > has zeros where i[x] != any element of j > and 1 where i[x] == any element of j. > > So for the example above the vector would look like this: > > c(1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0) > > > > can someone help me on this? > > ______________________________________________ > 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. >-- Henrique Dallazuanna Curitiba-Paran?-Brasil 25? 25' 40" S 49? 16' 22" O