I want my for loop to test for the presence of a term in a vector and return a value to a new vector. I'm not writing it correctly though. Here's what I have...> testfor = letters[1:5] > x = c("a", "b", "e", "f", "g") > result = rep(NA, length(testfor)) > > for (i in testfor){+ v = any(x == testfor[i]) + result[i] = v + }> > resulta b c d e NA NA NA NA NA NA NA NA NA NA I would like to get....>resultTRUE TRUE TRUE FALSE FALSE Thanks, MVS ----- MVS ====Matthew Van Scoyoc Graduate Research Assistant, Ecology Wildland Resources Department & Ecology Center Quinney College of Natural Resources Utah State University Logan, UT ====Think SNOW! -- View this message in context: http://r.789695.n4.nabble.com/help-with-for-loop-to-test-for-a-condition-in-a-vector-tp4649213.html Sent from the R help mailing list archive at Nabble.com.
David Winsemius
2012-Nov-11 00:02 UTC
[R] help with for loop to test for a condition in a vector
On Nov 10, 2012, at 2:07 PM, scoyoc wrote:> I want my for loop to test for the presence of a term in a vector and return > a value to a new vector. I'm not writing it correctly though. Here's what I > have... > >> testfor = letters[1:5] >> x = c("a", "b", "e", "f", "g") >> result = rep(NA, length(testfor)) >> >> for (i in testfor){ > + v = any(x == testfor[i]) > + result[i] = v > + } >> >> result > a b c d e > NA NA NA NA NA NA NA NA NA NA > > I would like to get.... > >> result > TRUE TRUE TRUE FALSE FALSE >Looks like yu want the first of these:> x %in% testfor[1] TRUE TRUE TRUE FALSE FALSE> testfor %in% x[1] TRUE TRUE FALSE FALSE TRUE -- David Winsemius, MD Alameda, CA, USA