[R] R equivalent for SQL query

andrija djurovic djandrija at gmail.com
Tue Apr 3 21:50:50 CEST 2012


Hi,

here are some solutions:

DF <- read.table(textConnection("
A       B       C
1       1       3
1       1       4
1       1       5
1       2       6
1       2       7
1       3       8 "), header=TRUE)

#using sqldf package
library(sqldf)
sqldf("select A, B, count(*)
      from DF
      group by A, B
      order by count(*) desc")

#using function table
as.data.frame(table(DF$A, DF$B))

As you can see, you can use sqldf package for performing sql queries
on R data frames.

Andrija



On Tue, Apr 3, 2012 at 8:26 PM, Steven Raemaekers <s.raemaekers at sig.eu> wrote:
> Hi,
>
> I have a query which I would like to translate into R, but I do not know how to do it in an easy way.
> Assume a data frame has columns A, B and C:
>
> A       B       C
> 1       1       3
> 1       1       4
> 1       1       5
> 1       2       6
> 1       2       7
> 1       3       8
>
> The query is as follows:
>
> select A, B, count(*)
> from data.frame
> group by A, B
> order by count(*) desc
>
> How do I translate this into R statements in such way that the result is a data frame structured as follows:
>
> A       B       count(*)
> 1       1       3
> 1       2       2
> 1       3       1
>
> Thanks,
>
> Steven
> ______________________________________________
> 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