[R] R equivalent for SQL query

jim holtman jholtman at gmail.com
Tue Apr 3 22:01:09 CEST 2012


Here is a solution using the data.table package:

> x <- read.table(text = "A       B       C
+ 1       1       3
+ 1       1       4
+ 1       1       5
+ 1       2       6
+ 1       2       7
+ 1       3       8", header = TRUE)
> require(data.table)
> x <- data.table(x)  # convert to a data.table
> # query
> result <- x[
+           , list(count = length(C))
+           , by = list(A,B)
+           ]
> # unsorted result
> result
     A B count
[1,] 1 1     3
[2,] 1 2     2
[3,] 1 3     1
> # sorted result
> result[order(result$count, decreasing = TRUE), ]
     A B count
[1,] 1 1     3
[2,] 1 2     2
[3,] 1 3     1
>
>


On Tue, Apr 3, 2012 at 3:50 PM, andrija djurovic <djandrija at gmail.com> wrote:
> 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.
>
> ______________________________________________
> 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.



-- 
Jim Holtman
Data Munger Guru

What is the problem that you are trying to solve?
Tell me what you want to do, not how you want to do it.



More information about the R-help mailing list