Eric
Eric

Reputation: 1

R: Using sqldf and insert to create a dataframe

I am trying to create a dataframe using sqlf and sql insert. Here's a simple version of my code

d2 = data.frame(x=runif(10))
sqldf(c("create table d1(min_x real, max_x real)", 
        "insert into d1 select min(x), max(x) from d2", 
        "select * from d1"))

The output is

       min_x     max_x
1 0.05290026 0.9427019

Now I want to use d1 in my R code, but if I enter

d1

R responds

> d1
Error: object 'd1' not found

I have tried this using SQLite and RH2 with the same results.

How do I use d1 in R?

Upvotes: 0

Views: 3231

Answers (1)

White River
White River

Reputation: 13

sqldf, when used with the default driver SQLite will setup an on-the-fly in-memory database which will be destroyed upon exit. The only way to save the object is to assign it with :

d1 <- sqldf(c("create table d1(min_x real, max_x real)", 
    "insert into d1 select min(x), max(x) from d2", 
    "select * from d1"))

You can then use it in your R code:

> print(d1)
  min_x     max_x
1 0.0558218 0.8966438

Upvotes: 1

Related Questions