Re: [R] building a formula string bit by bit ..

From: Charilaos Skiadas <cskiadas_at_gmail.com>
Date: Tue, 06 May 2008 15:25:40 -0400

I would actually go with this:

bits=c(1, 0, 1, 1, 0)
paste("X", which(bits==1), sep=".",collapse="+")

No need for the vars variable. Though admittedly it breaks down if bits is identically 0.

Haris Skiadas
Department of Mathematics and Computer Science Hanover College

On May 6, 2008, at 3:11 PM, Jorge Ivan Velez wrote:

> Hi Esmail,
>
> Try this:
>
> vars=c('X.1', 'X.2', 'X.3', 'X.4', 'X.5')
> bits=c(1, 0, 1, 1, 0)
> paste(vars[which(bits==1)],collapse="+")
>
> HTH,
>
> Jorge
>
>
>
> On Tue, May 6, 2008 at 3:06 PM, Esmail Bonakdarian
> <esmail.js_at_gmail.com>
> wrote:
>
>> Hello,
>>
>> Still a newbie with R, though I have learned a lot from reading
>> this list. I'm hoping someone can help with this question:
>>
>> I have two vectors, one for variables, and one for bits.
>>
>> I want to build a string (really a formula) based on the values in my
>> vector of 1s and 0s in bits. If I have a one, I want to include the
>> corresponding entry in the vars vector, otherwise ignore it. Of
>> course
>> the "bits" vector will not stay the same.
>>
>> So for example:
>>
>> vars=c('X.1', 'X.2', 'X.3', 'X.4', 'X.5')
>>
>> bits=c(1, 0, 1, 1, 0)
>> ones=which(bits==1)
>>
>> should yield:
>>
>> "X.1 + X.3 + X.4"
>>
>> where as
>>
>> bits=c(1, 1, 0, 0, 0)
>>
>> would yield
>>
>> "X.1 + X.2"
>>
>> the "which" operator gives me the index values, is there an easy and
>> *efficient* way to build this string so that I can pass it on to glm?
>> I can probably hack some ugly code together to do this, but it won't
>> be efficient, and it won't be elegant :-)
>>
>> Can anyone help?
>>
>> Thanks!



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. Received on Tue 06 May 2008 - 19:29:16 GMT

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.2.0, at Tue 06 May 2008 - 19:30:35 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.

list of date sections of archive