How can I pass R variable into sqldf?

假装没事ソ 提交于 2019-12-03 18:05:51

问题


I have some query like this:

sqldf("select TenScore from data where State_P = 'AndhraPradesh'")

But I have "AndhraPradesh" in a variable stateValue. How can I use this variable in a select query in R to get the same result as above.

Please show me the syntax.


回答1:


You can use sprintf:

sqldf(sprintf("select TenScore from data where State_P = '%s'", stateValue))



回答2:


See Example 5 on the sqldf GitHub page.


Example 5. Insert Variables

Here is an example of inserting evaluated variables into a query using gsubfn quasi-perl-style string interpolation. gsubfn is used by sqldf so its already loaded. Note that we must use the fn$ prefix to invoke the interpolation functionality:

> minSL <- 7
> limit <- 3
> species <- "virginica"
> fn$sqldf("select * from iris where \"Sepal.Length\" > $minSL and species = '$species' limit $limit")

  Sepal.Length Sepal.Width Petal.Length Petal.Width   Species
1          7.1         3.0          5.9         2.1 virginica
2          7.6         3.0          6.6         2.1 virginica
3          7.3         2.9          6.3         1.8 virginica



回答3:


You can also use fn$sqldf :

fn$sqldf("select TenScore from data where State_P = '$stateValue'")



来源:https://stackoverflow.com/questions/7547950/how-can-i-pass-r-variable-into-sqldf

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!