R accessing DB query results by column and row number
I am new to R language. 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. 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(开发者_如何学Python"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.
精彩评论