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

Marc Schwartz marc_schwartz at comcast.net
Tue May 6 21:36:05 CEST 2008


Marc Schwartz wrote:
> Esmail Bonakdarian 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!
> 
> Depending upon other factors, there may be a better and more general 
> approach to what you are trying to do relative to selecting subsets of 
> IV's. However, given the information you have provided:
> 
>   vars <- c('X.1', 'X.2', 'X.3', 'X.4', 'X.5')
>   bits <- c(1, 0, 1, 1, 0)
> 
>   > paste(vars[bits == 1], collapse = " + ")
>   [1] "X.1 + X.3 + X.4"
> 
> 
>   bits <- c(1, 1, 0, 0, 0)
> 
>   > paste(vars[bits == 1], collapse = " + ")
>   [1] "X.1 + X.2"
> 
> 
> You will then need to use as.formula() to coerce the resultant vectors 
> before passing them to the model function.

One other tweak here, if you use TRUE/FALSE rather than 1/0 to define 
the positions and this gets rid of the need for 'vars':

   bits <- c(TRUE, FALSE, TRUE, TRUE, FALSE)

   > paste("X", which(bits), collapse = " + ", sep = ".")
   [1] "X.1 + X.3 + X.4"


HTH,

Marc



More information about the R-help mailing list