迭代来自 R 的 SQLite 结果
Iterate over SQLite results from R
我是使用 R 作为语言编程的新手。现在我正在尝试对查询结果进行基本循环,但我做不到,让我们看看:
我有一个名为 RDB.sqlite 的数据库和一个名为 table 的 PERDIDAS,具有以下结构
|编号 |时期 |勇气 |
我有以下 R 代码:
library("RSQLite")
con <- dbConnect(SQLite(), dbname = "bd/RDB.sqlite")
periodo <- function(num){
results<-dbGetQuery(con, paste("SELECT PERIODO,VALOR FROM PERDIDAS WHERE PERIODO = ",num,""))
# WHEN I TRY ITERATE OVER THE RESULTS...
for (result in results){
print(result)
}
}
results(2)
当我 运行 这个脚本时,它只是调用结果函数,将它作为参数传递给它 2。这就是我在控制台上看到的:
[1] 2 2 2 2
[1] 2219.398 2218.256 2209.780 2236.723
怎么了?我不知道如何正确地遍历所有元素..你能帮我吗?我希望在控制台上看到类似的内容:
[1] 2219.398
[2] 2218.256
[3] 2209.780
[4] 2236.723
使用 dbGetQuery()
的返回结果是一个数据框,而不是 for
循环假设的列表。
因此,只需在查询命令后像查看任何其他数据框一样查看结果:
View(results) # pop-up window of data frame
print(results) # console output of data frame
for (i in 1:nrow(results)) {
print(results[i,]) # iterate through each row of data frame
}
for (i in 1:nrow(results)) {
print(results$column[[i]]) # iterate through each row of selected column in df
}
我是使用 R 作为语言编程的新手。现在我正在尝试对查询结果进行基本循环,但我做不到,让我们看看:
我有一个名为 RDB.sqlite 的数据库和一个名为 table 的 PERDIDAS,具有以下结构
|编号 |时期 |勇气 |
我有以下 R 代码:
library("RSQLite")
con <- dbConnect(SQLite(), dbname = "bd/RDB.sqlite")
periodo <- function(num){
results<-dbGetQuery(con, paste("SELECT PERIODO,VALOR FROM PERDIDAS WHERE PERIODO = ",num,""))
# WHEN I TRY ITERATE OVER THE RESULTS...
for (result in results){
print(result)
}
}
results(2)
当我 运行 这个脚本时,它只是调用结果函数,将它作为参数传递给它 2。这就是我在控制台上看到的:
[1] 2 2 2 2
[1] 2219.398 2218.256 2209.780 2236.723
怎么了?我不知道如何正确地遍历所有元素..你能帮我吗?我希望在控制台上看到类似的内容:
[1] 2219.398
[2] 2218.256
[3] 2209.780
[4] 2236.723
使用 dbGetQuery()
的返回结果是一个数据框,而不是 for
循环假设的列表。
因此,只需在查询命令后像查看任何其他数据框一样查看结果:
View(results) # pop-up window of data frame
print(results) # console output of data frame
for (i in 1:nrow(results)) {
print(results[i,]) # iterate through each row of data frame
}
for (i in 1:nrow(results)) {
print(results$column[[i]]) # iterate through each row of selected column in df
}