【问题标题】:R accessing DB query results by column and row numberR按列和行号访问数据库查询结果
【发布时间】:2009-12-29 07:21:28
【问题描述】:

我是 R 语言的新手。我已成功将查询的结果集加载到变量中。现在我想按列名和行号访问结果集数据。我需要验证它是否为 Null(在结果中显示为 ),然后使用 PHP 通过 bat 文件发送邮件。我的示例代码如下。

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")
}

我还想比较一个字符串结果,如下所示。

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

但我认为我使用了错误的语法。请帮忙,因为我无法获得进行这些比较的正确语法。

【问题讨论】:

    标签: r syntax comparison


    【解决方案1】:

    试试这个:

    # 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")
    }
    

    你也可以这样做

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

    按行和列索引进行索引。

    最后,NA 测试不同于字符串比较——您需要is.null()is.na(),因为这可能会被 ODBC 访问转换。

    【讨论】:

    • 非常感谢。 is.na() 是我正在寻找的那个。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-01-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-06
    • 2019-01-23
    • 1970-01-01
    相关资源
    最近更新 更多