问题
Edited the question to be clearer as requested.
Note that the inputs are provided in reproducible form in the Note at the end.
I am using sqldf to join two datasets in R
The code returns a dataset with the with the original column names, ignoring the "as" in the select statement.
output_1 <- sqldf("SELECT a.MRN, a.TestDate, b.TestDate as Date2
from a
inner join b
on a.MRN=b.MRN order by a.MRN, a.TestDate")
giving:
> sapply(output_1,colnames)
$MRN
NULL
$TestDate
NULL
$TestDate
NULL
> head(output_1)
MRN TestDate TestDate
1 10013 2013-09-10 2014-05-20
2 10013 2013-09-10 2014-05-20
3 10013 2013-09-10 2014-05-20
4 10013 2013-09-10 2014-11-18
5 10013 2013-09-10 2015-05-19
6 10013 2013-10-15 2014-05-20
Any idea why, or how to get the right field names in the output?
A workaround I developed is to rename TestDate in the second dataset (b) before using the inner join call. But I prefer to get the "as" to work as it does in other applications.
Any ideas?
Please note that my focus is on the column name only. And thanks!
Note: Here are a
and b
in reproducible form:
Lines_a <- "MRN TestDate
10013 2013-09-10
10013 2013-10-15
10013 2013-11-19
10013 2014-05-20
10013 2014-11-18
10051 2010-02-10"
a <- read.table(text = Lines_a, header = TRUE)
Lines_b <- "MRN TestDate
10013 2014-05-20
10013 2014-05-20
10013 2014-05-20
10013 2014-11-18
10013 2015-05-19
10051 2010-05-26"
b <- read.table(text = Lines_b, header = TRUE)
回答1:
Assuming that you are using the H2 database (which would be the case if the RH2 package is loaded) then I am able to reproduce the output in the question. It may represent a bug in H2. Try using sqlite instead by (i) not loading RH2 or (ii) detaching it if loaded or (iii) if neither of these are desirable using sqldf(..., drv = "SQLite")
Here we show that we can reproduce the output shown in the question with RH2 loaded:
library(RH2)
library(sqldf)
output_1 <- sqldf("SELECT a.MRN, a.TestDate, b.TestDate as Date2
from a
inner join b
on a.MRN=b.MRN order by a.MRN, a.TestDate")
giving:
> head(output_1)
MRN TestDate TestDate
1 10013 2013-09-10 2014-05-20
2 10013 2013-09-10 2014-05-20
3 10013 2013-09-10 2014-05-20
4 10013 2013-09-10 2014-11-18
5 10013 2013-09-10 2015-05-19
6 10013 2013-10-15 2014-05-20
来源:https://stackoverflow.com/questions/36553170/r-sqldf-renaming-a-field-in-a-select-statement