如何将 R 变量传递到 sqldf 中?

发布于 2024-12-06 07:34:14 字数 227 浏览 3 评论 0原文

我有一些这样的查询:

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

但是我在变量 stateValue 中有 "AndhraPradesh"。如何在 R 的选择查询中使用此变量以获得与上面相同的结果。

请告诉我语法。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

喜爱纠缠 2024-12-13 07:34:14

您可以使用 sprintf:

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

You can use sprintf:

sqldf(sprintf("select TenScore from data where State_P = '%s'", stateValue))
烟沫凡尘 2024-12-13 07:34:14

请参阅 sqldf GitHub 页面


示例 5. 插入变量

下面是使用 gsubfn 准 Perl 样式字符串插值将求值变量插入到查询中的示例。 gsubfn 由 sqldf 使用,因此它已经加载。请注意,我们必须使用 fn$ 前缀来调用插值功能:

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

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 it is 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
在你怀里撒娇 2024-12-13 07:34:14

您还可以使用 fn$sqldf

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

You can also use fn$sqldf :

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文