[R] Assigning value of subset argument in "subset" function

David Winsemius dwinsemius at comcast.net
Mon Aug 24 04:19:28 CEST 2009


On Aug 23, 2009, at 10:12 PM, David Winsemius wrote:

>
> On Aug 23, 2009, at 9:56 PM, Steven Kang wrote:
>
>> Dear R users,
>>
>> I am using "subset" function to filter out specific conditions and  
>> would
>> like to use the value of subsetted argument as a name of an object.
>>
>> Specifically, from the following statement:
>>
>>    a <- subset(dat, dat$x == "A" & dat$xx == 1 & dat$xxx == "AB" &  
>> dat$y
>> == "B" & dat$yy == 2)
>> I would to assign the value of the 3rd subset argument (i.e. "AB")  
>> as an
>> object's name such as:
>>
>>    a.AB <- sum(a$z)
>
> Sounds like you need to read FAQ 7.21:
>
> http://cran.r-project.org/doc/FAQ/R-FAQ.html#How-can-I-turn-a-string-into-a-variable_003f
>
> Perhaps, ... lightly tested, of course, because no reproducible data  
> provided:
>
> assign( paste("a.",  sum(a$z), sep=""),
>        subset(dat,x == "A" & xx == 1 & xxx == "AB" &  y== "B" & yy  
> == 2)   )
>
> # you do not need the "dat$"'s in the subset.
>
> > a <- data.frame(x=1:4, y=4:7, xx=8:11, xxx=12:15)
> > a
>  x y xx xxx
> 1 1 4  8  12
> 2 2 5  9  13
> 3 3 6 10  14
> 4 4 7 11  15

Arrgh. Trimmed out the code:

assign( paste("a.",  sum(a$x), sep=""),
          subset(a,x == 1 & xx == 8 )   )

>
> > a.10
>  x y xx xxx
> 1 1 4  8  12
> -- 

David Winsemius, MD
Heritage Laboratories
West Hartford, CT




More information about the R-help mailing list