简体   繁体   English

R按列和行号访问数据库查询结果

[英]R accessing DB query results by column and row number

I am new to R language. 我是R语言的新手。 I have successfully loaded a query's resultset into a variable. 我已成功将查询的结果集加载到变量中。 Now I want to access the resultset data by column name and row number. 现在,我想按列名和行号访问结果集数据。 And I need to verify if it is Null (it is shown as < NA > in result) then send a mail by bat file with PHP. 而且我需要验证它是否为Null(结果显示为<NA>),然后使用PHP通过bat文件发送邮件。 My sample code is below. 我的示例代码如下。

library(RODBC)
newconn = odbcConnect("db", uid="uid", pwd="pwd") 
new <- sqlQuery(newconn,"SELECT COL1, COL2 FROM TABLE1;", errors = TRUE, 1)
if(new$COL1[3] == "<NA>"){
system("sendmail.bat")
}else{
print ("failed")
}

Also I would like to compare a string result like below. 我也想比较如下字符串结果。

if(new$COL2[10] == 'MYSTRING'){
print("success")
}

But I think I am using wrong syntax. 但是我认为我使用了错误的语法。 Please help as I am not able to get the correct syntax for doing these comparisons. 请帮忙,因为我无法获得进行这些比较的正确语法。

Try this: 尝试这个:

# I'd avoid new as a variable name
newdata <- sqlQuery(newconn,"SELECT COL1, COL2 FROM TABLE1;", errors = TRUE, 1)

# index data frame by row number and column name

if (newdata[3, "COL1"] == "someValue") {
     print("found someValue")
} else {
     print ("failed")
}

You can also do 你也可以

if (newdata[3, 2] == "MYSTRING")

to index by row and column index. 按行和列索引编制索引。

Lastly, testing for NA is different than string comparison -- you need is.null() or is.na() as this may get converted by the ODBC access. 最后,测试NA不同于字符串比较-您需要is.null()is.na()因为这可能会通过ODBC访问来转换。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM