0

R sqldfで列名をパラメータとしてSQLに渡すにはどうすればよいですか?

ない

q <- "Q10"

A = fn$sqldf('SELECT * FROM Customer WHERE $q < 100')

また

q <- "Q10"

A = fn$sqldf('SELECT * FROM Customer WHERE '$q' < 100')

動作します。

4

3 に答える 3

2

解決:

コマンドを使用pasteして、変数と文字列を連結できます。

> library(sqldf)
> my_names <- names(sqldf("select * from iris limit 10"))
> sqldf(paste("select",my_names[1], "from iris limit 2", sep=" "))
      Sepal_Length
1          5.1
2          4.9

またはfn$文字列補間を実行するために使用すると、最後の行は次のように記述できます。

> fn$sqldf("select `my_names[1]` from iris limit 2")

潜在的な問題:

sqldf を使用してクエリを実行しようとすると、名前が異なる場合があります。たとえば、データセットのデフォルト名irisは次のとおりです。

> names(iris)
[1] "Sepal.Length" "Sepal.Width"  "Petal.Length" "Petal.Width"  "Species" 

ただし、列名を使用してクエリを作成しようとする場合は、名前を別の方法でフォーマットする必要があります。

> sqldf("select * from iris limit 1")
  Sepal_Length Sepal_Width Petal_Length Petal_Width Species
1          5.1         3.5          1.4         0.2  setosa    

これは公式の説明です

Here is an example of sorting and limiting output from an SQL select statement on the iris data frame that comes with R. Note that although the iris dataset uses the name Sepal.Length the RSQLite layer converts that to Sepal_Length.

それが私のソリューションの理由です。私は最初に の代わりに select ステートメントmy_namesから変数を作成しました。sqldfnames(iris)

于 2013-11-25T05:00:47.367 に答える