[R] selection part of "subset"

Marc Schwartz marc_schwartz at me.com
Thu Jan 5 17:24:54 CET 2012


On Jan 5, 2012, at 10:04 AM, Christof Kluß wrote:

> Hi
> 
> the output should look like     r <- subset(tab, a==v)
> but now I have something like   r <- subset(tab, "a"==v)
> and                             r <- subset(tab, [["a"]]==v)
> does not work :(
> 
> greetings
> Christof
> 
> Am 05-01-2012 16:51, schrieb Christof Kluß:
>> Hi
>> 
>> I want to do something like
>> 
>> a <- c(10,20,15,43,76,41,25,46)
>> tab <- data.frame(a)
>> 
>> name <- "a"
>> 
>> for (v in unique(tab[[name]])) {
>>  r <- subset(tab, name==v)   # this does not work
>>  ...
>> }
>> 
>> i.e. a "string" on the left side of the select expression (subset). How
>> could I solve this?
>> 
>> thx
>> Christof


It is not entirely clear what you want as an end result, especially given that you only have one column in 'tab' and that column only has unique entries.

That being said, if your goal is to subset a data frame based upon unique values in one or more columns, you may want to look at ?split.

Taking your 'tab' as an example, using split() would get you a list of data frames, one per unique value in 'a':

> tab
   a
1 10
2 20
3 15
4 43
5 76
6 41
7 25
8 46


> split(tab, tab$a)
$`10`
   a
1 10

$`15`
   a
3 15

$`20`
   a
2 20

$`25`
   a
7 25

$`41`
   a
6 41

$`43`
   a
4 43

$`46`
   a
8 46

$`76`
   a
5 76


HTH,

Marc Schwartz



More information about the R-help mailing list