I'm working with rmongodb and rmongodbHelper packages and i've built this function.
CUPS_CP_TAR36 <- function(codi,cant){
cups <- vector()
query <- json_to_bson('{"clLst.U_COD_POSTAL": codi, "clLst.TARIFA_ATR": {"$in": "3.0A","3.1A","6.1"]}}')
output <- json_to_bson('{"id":1}')
cursor <- mongo.find(mongo, sips, query, fields=output, limit=cant)
k = 0
while(mongo.cursor.next(cursor)){
k = k + 1
cups[k] <- mongo.bson.value(mongo.cursor.value(cursor), "_id")
}
return(cups)
}
but when I try to use it:
example <- CUPS_CP_TAR36(codi="08036", cant=10)
I get the following error and really dont know why, i'm not used to write my own functions:
Error in eval(expr, envir, enclos) : object 'codi' not found
Thanks!
Try latest rmongodb version from github. bson from json works out of the box. Moreover mongo.bson.to.list works fine for every case, so you dont't need to construct bson from json. I have plans to push new version of the package to CRAN next week.
library(devtools)
install_github("mongosoup/rmongodb")
query <- json_to_bson('{"clLst.U_COD_POSTAL": codi, ...}')
json_to_bson() expects a JSON string. The string you provide is not valid JSON, just as {"key":val} is not valid - while {"key":"val"} or {"key":3.14} are valid.
Of course codi isn't even intended by you to be a string in your case but to be a variable. But as you write the code there is no way for R to know about that.
So you might write:
query <- json_to_bson(sprintf('{"clLst.U_COD_POSTAL": "%s", ...}',codi))
The equivalent expression with your value of codi is then:
query <- json_to_bson('{"clLst.U_COD_POSTAL": "08036", ...}')
The reason why there is an error message involving eval() is b/c I wrote the interpretation of the JSON very, very simple - mind this "package" is merely a workaround and hopefully superfluous very soon.
The JSON is turned into a list()-expression using string-substitution and then eval()ed.
rmongodbHelper / R / json_to_list.R:
json_to_list <- function(json) {
json <- gsub("\n","",json)
json <- gsub("\\{\\}","list()",json)
[...]
json <- gsub("\\$","_$",json)
return(eval(parse(text = json)))
}
Further details: MongoDB – State of the R
Related
Below is a snippet of my code that I use in R to extract IDs from a PostgreSQL database. When I run the function I get the following warning message from R:
In result_create(conn#ptr, statement) :
Closing open result set, cancelling previous query
How do I avoid this warning message from happening without making use of options(warn=-1) at the beginning of my code, suppressing the warning instead of
con <- dbConnect(RPostgres::Postgres(),
user = "postgres",
dbname = "DataBaseName",
password = "123456",
port = 5431)
get_id <- function(connection, table){
query <- toString(paste("SELECT id FROM ", table, sep = ""))
data_extract_query <- dbSendQuery(connection, query)
data_extract <- dbFetch(data_extract_query)
return(data_extract)
}
get_id(con, "users")
I found a method for solving the problem.
I found a thread on GitHub for RSQLite a https://github.com/r-dbi/RSQLite/issues/143. In this thread, they explicitly set n = -1 in the dbFetch() function.
This seemed to solve my problem, and the warning message did not show up again by editing the code like the following:
data_extract <- dbFetch(data_extract_query, n = -1)
The meaning of n is the number of rows that the query should return. By setting this to -1 all rows will be retrieved. By default, it is set to n = -1 but for some reason, in this build of R (3.6.3) the warning will still be shown.
Calling ?dbFetch in R you can see more information on this. I have included a snippet from the R-help page:
Usage
dbFetch(res, n = -1, ...)
fetch(res, n = -1, ...)
Arguments
res An object
inheriting from DBIResult, created by dbSendQuery().
n maximum number of records to retrieve per fetch. Use n = -1 or
n = Inf to retrieve all pending records. Some implementations may
recognize other special values.
... Other arguments passed on to methods.
This issue comes up with other database implementations if the results are not cleared before submitting a new one. From the docs of DBI::dbSendQuery
Usage
dbSendQuery(conn, statement, ...)
...
Value
dbSendQuery() returns an S4 object that inherits from DBIResult. The result set can be used with dbFetch() to extract records. Once you have finished using a result, make sure to clear it with dbClearResult(). An error is raised when issuing a query over a closed or invalid connection, or if the query is not a non-NA string. An error is also raised if the syntax of the query is invalid and all query parameters are given (by passing the params argument) or the immediate argument is set to TRUE.
To get rid of the warning the get_id() function must be modified as follows:
get_id <- function(connection, table){
query <- toString(paste("SELECT id FROM ", table, sep = ""))
data_extract_query <- dbSendQuery(connection, query)
data_extract <- dbFetch(data_extract_query)
# Here we clear whatever remains on the server
dbClearResult(data_extract_query)
return(data_extract)
}
See Examples section in help for more.
I am trying to run the below simple function in R studio
a<-testfunc15(state,outcome)
{
st<-state
out<-outcome
print(st)
tempdff<-healthcareoutcome[healthcareoutcome$State==st,]
tempdff
}
When i copy and paste of the R prompt of the R studio ,i get an error :
Error: could not find function "testfunc15"
> {
+
+ st<-state
+ out<-outcome
+ print(st)
+ tempdff<-healthcareoutcome[healthcareoutcome$State==st,]
+ tempdff
+
+ }
Error: object 'state' not found
when i try to source it :source("testfunc15.R")
then i get this error :
Error in eval(expr, envir, enclos) : could not find function"testfunc15"
I am saving the file in the same getwd() as other functions ,other functions are working fine.
Where am i going wrong ?
I couldn't find an answer on stackoverflow though there were many questions with the same description.
Please help
The first line of your code is telling R to store the result of testfunc15(state, outcome) in a. It is not defining the function.
Also your function as written here doesn't exist. It should be, as mentionned by Dason, either :
testfunc15 = function (state, outcome) or testfunc15 <- function (state, outcome)
And the end could be return(tempdiff) or tempdiff
I get an Argument is of length zero error when I run the below code
The code is from this blog -http://giventhedata.blogspot.in/2012/08/r-and-web-for-beginners-part-iii.html.
library(XML)
url<- "http://news.bbc.co.uk/2/hi/uk_politics/8044207.stm"
first<-"Abbott, Ms Diane"
url.tab <- readHTMLTable(url)
for (i in 1:length(url.tab)){
if (as.character(url.tab[[i]][1,1]) == first ) {print(first)}
}
I know that the url.tab[[5]][1,1]) does contain the string "Abbott, Ms Diane", and when I run IF statement in isolation replacing the i with 5, it runs fine. Any help would be appreciated. I also tried declaring i<-1 upfront. DInt change anything.
Some of your tables are in fact NULL.
So you have to test for is.null before trying to subset the table:
for (i in 1:length(url.tab)){
this.tab <- url.tab[[i]]
if(!is.null(this.tab)) if(as.character(this.tab[1,1]) == first ) {print(first)}
}
[1] "Abbott, Ms Diane"
I am completely new to R.
I am trying to use the dist object with a custom function based on the specification here, but I was unable to pass the custom function directly by name, so I tried to add it using the registry described here, but it appears that I am missing a library.
However, I'm not sure which library I need and cannot find a reference to find the name of the library.
Here's a code sample that I'm trying to run:
library(cluster)
myfun <- function(x,y) {
numDiffs <- 0;
for (i in x) {
if (x[i] != y[i])
numDiffs <- numDiffs + 1;
}
return(numDiffs);
}
summary(pr_DB)
pr_DB$set_entry(FUN = myfun, names = c("myfun", "vectorham"))
pr_DB$get_entry("MYFUN")
Here's the error:
Error in summary(pr_DB) : object 'pr_DB' not found
Execution halted
You need to learn the conventions used by R help pages. That "{proxy}" at the top of the page you linked to is really the answer to your question. The convention for the help page construction is "topic {package_name}".
I am using the following function to select values from a table.Table name is given as the parameter to that function.If the table does not exist an error generated and the execution is stoped.I want to do something if the table is not found.Is it possible in R? something like try-catch exception ?
library('RSQLite')
getData <- function(portfolio){
lite <- dbDriver("SQLite", max.con = 25)
db <- dbConnect(lite, dbname = "portfolioInfo.db")
res <- dbSendQuery(db, paste("SELECT * from ",portfolio," ",sep=""))
data <- fetch(res)
return (data)
}
getData("table1")
One way to do this would be to check the class of the data that is returned.
I am not familiar with RSQLite but I guess it will return a dataframe if the table is found and a text error when not?
So a possibility would be to check whether or not an error is raised:
checkQueryResult<-function(data){
if(class(data)=='data.frame') cat('SQL execution worked!')
else cat('Something went wrong, table does not exist?')
}
checkQueryResult(getData("table1"))
But maybe the RSQLite package already has error handling stuff built in?