[R] subset problem

andrija djurovic djandrija at gmail.com
Thu Mar 29 07:45:41 CEST 2012


Hi. You can try this:

df[type%in%type_list, ]

You can  also use sqldf package and subset data frames usign sql statements:

library(sqldf)

df <- data.frame(x1=1:10, type=10:1)
type_list <- data.frame(index=seq(1,10,by=2))

sqldf("select df.*
      from df
      where df.type in (select * from type_list)")


Andrija



On Thu, Mar 29, 2012 at 7:25 AM, reeyarn <reeyarn at gmail.com> wrote:
> Hi,
>
> If my data frame "df" has a index "type", I want to get a subset such
> that the type belongs to a "type_list";
> using sql, I want
>  SELECT name, type FROM df
>    WHERE type in type_list;
>
> Now in R I have to write a loop like
>  mysubset<- df [ df$type == type_list[1], ]
>  for (type1 in type_list[ 2: length (type_list) ] ) {
>    mysubset<-cbind (mysubset, df [ df$type == type1, ])
>  }
>
> What is the natural way of doing this in R? Is it possible to use
> subset() to attain this?
> Thanks!
>
> Best,
> Reeyarn
>
> On Fri, Dec 3, 2010 at 11:26 AM,  William Dunlap <[hidden email]> wrote:
>> HI,
>> I have a dataframe like this:
>> name    type
>> A          t1
>> B           t2
>> C          t1
>> D           t4
>> E           t3
>> F            t2
>> how can I have a "sub dataframe" based with the column "type" like this:
>> (for type = t1)
>> name    type
>> A          t1
>> C          t1
>> D           t1
>
> Hi,
>
> Let's say your data.frame is stored in a variable named "df":
>
> R> subset(df, type == 't1')
>
> Read the help files:
>
> R> ?subset
>
> Also take a look at ?split
>
> -steve
>
> ______________________________________________
> 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.



More information about the R-help mailing list