Marcus R
Marcus R

Reputation: 245

Paste logical conditions in R

I have now rewriten my problem to make it clearer

I want to replace a condition like this where var is a variable in dataframe (dataframe$var) with a paste or other solution as I do have so many condition values(?) (a, b and c in my example).

subdataframe<-dataframe[var=="a"|var=="b"|var=="c",]

I have tried to make a list(?) of the condtion values.

sample<-c("a","b","c")

And to then use paste to make the logical condition

subdataframe<-dataframe[paste("var",sample,sep="==",collapse="|"),]

But that doesn't work

Help please =)

Marcus

Upvotes: 1

Views: 1523

Answers (2)

Martin
Martin

Reputation: 1622

Joshua is right in questioning the use of parse.

Still, here's the answer to your question:

 paste("var==\"",sample, "\"",sep="",collapse="|")

This will get you the desired string, inculding quotes.

Upvotes: 1

Joshua Ulrich
Joshua Ulrich

Reputation: 176728

Heed fortune(106):

> fortune(106)

If the answer is parse() you should usually rethink the question.
   -- Thomas Lumley
      R-help (February 2005)

So I would encourage you to rethink what you're trying to do...

I would guess that you could use match or %in% to achieve your desired result, but you haven't told us what you're trying to do.

> sample <- c("a","b","c")
> var <- c("a","d","c")
> eval(parse(text=paste("var==",sample,"",sep="'",collapse="|")))
[1]  TRUE FALSE  TRUE
> var %in% sample
[1]  TRUE FALSE  TRUE

Upvotes: 7

Related Questions