What does the “slot doesn't exist” error message mean? - r

I'm trying to write an object and access to his parameters. I've got two files, menus.R, where I define the object, and main.R, where I use the object and try to access to a slot (parameter).
The code of both files are next:
menus.R
menu <- setClass("menu", slots=list(competition="numeric", stats="numeric"))
setMethod("show", "menu", function(object){
while (TRUE){
#Clean console
cat("\014")
cat("COMPARATIVA ENTRE EQUIPOS DE LA MISMA COMPETICION\n")
cat("-------------------------------------------------\n\n")
cat("1. Comparativa entre clubes de Liga DIA\n")
cat("2. Comparativa entre clubes de Liga Femenina 2 - Grupo 'A'\n")
cat("3. Comparativa entre clubes de Liga Femenina 2 - Grupo 'B'\n")
cat("0. Salir\n\n")
option <- readline("Selecciona opción: ")
option <- suppressWarnings(as.numeric(option))
if (!is.na(option)){
if (option == 1){
object#competition <- 14
}
if (option == 2){
object#competition <- 22
}
if (option == 3){
object#competition <- 23
}
readline("Espera ...")
if (option == 0)
break
}else{
readline("No es un número. Pulsa una tecla para introducir otra opción.")
}
}
})
main.R
menu(competition=0, stats=0)
print(menu#competition)
getClass(class(menu))
When I call menu(competition=0, stats=0) I can see what the method show gives me to me. This is correct. In show method I assign a value to competition. When I exit from show method the next instruction is print(menu#competition) and here is where I've got this error:
Error in print(menu#competition) : there is no a slot with name
"competition" for this object class "classGeneratorFunction"
Then with getClass(class(menu)) I've got this:
What am I doing wrong? How can I get access to competition or stats?

You are confusing the object constructor with the object itself.
menu(competition = 0, stats=0) generates you a new object of class menu, but you fail to save it somewhere, so it prints on the screen. Therefore your first, correct output.
But then, you want to manipulate the object. But you didn't save it! Instead, you try to manipulate the "object factory", menu(). The Type of the "object factory" is classGeneratorFunction, that's what you see.
This should work:
myMenuObject <- menu(competition=0, stats=0)
print(myMenuObject)
print(myMenuObject#competition)
getClass(class(myMenuObject))

Related

How to properly run an API GET request with ODBC access?

Im trying to create an API that receives an ID, queries a MSSQL database and returns back a result.
#* #apiTitle IdCx
#* #apiDescription A test
#* #get /IdCx
#*
apiFn <- function(id) {
require(odbc)
require(glue)
dbcon <- dbConnect(odbc::odbc()
,dsn = "test"
,database = "testDB"
,uid = user1
,pwd = pass1
,Trusted_Connection= "No"
,encoding = "UTF-8"
)
IdCx = dbGetQuery(dbcon, glue_sql('SELECT max (CC.IdCx)
FROM table CC
where IdA in ({id})
'))
as.numeric(IdCx)
}
After creating the R file main.R, I execute it:
apiTest <- pr("main.R")
pr_run(apiTest)
But I get this error
{
"error": "500 - Internal server error",
"message": "Error in h(simpleError(msg, call)): error in evaluating the argument 'statement' in selecting a method for function 'dbGetQuery': error in evaluating the argument 'conn' in selecting a method for function 'dbQuoteLiteral': el argumento \".con\" is missing, with no default\n"
}
But if I deliberately insert a fixed id=1365350 inside the code (just for testing), the API will return a correct result
#* #apiTitle IdCx
#* #apiDescription A test
#* #get /IdCx
#*
apiFn<- function(id) {
require(odbc)
require(glue)
id=1365350
dbcon <- dbConnect(odbc::odbc()
,dsn = "venus"
,database = "DWHICV"
,uid = Sys.getenv("sql_reportes_id")
,pwd = Sys.getenv("sql_reportes_pw")
,Trusted_Connection= "No"
,encoding = "UTF-8"
)
IdCx = dbGetQuery(dbcon, glue_sql('SELECT max (CC.IdCx)
FROM hceCxCirugia CC
where IdAtencion in ({id})
'))
as.numeric(IdCx)
}
Including #* #param IdA wont fix the error
Figured it out. Eventhough I never used the parameter .con inside the glue_sql function when running it from RStudio, apparently is mandatory when using plumber API.
IdCx = dbGetQuery(dbcon, glue_sql('SELECT max (CC.IdCx)
FROM table CC
where IdA in ({id})
,.con = dbcon))

Trying to iterate thru a web class using Selnium Python 3.10

Im trying to iterate thru a class element in aour website to download each report using selenium and python, the problem is tha t the reports are variable some day is 8 another day is 9 other day is 12 so I cant harcode the logic for each one must be dynamic, I almos try everything I searched in google, and nothing works, I found something that is as follows:
a = driver.find_elements(By.CLASS_NAME, "k-link")
enter image description here
I need something like that but the result must be something that selenium understand like xpath, class, selector or something lake that in order to avoid hardcoding.
here is the image of the website specifically the tabs of the class
enter image description here
I really will apreciate your help. Thanks in advance.
`thats my python code``
def elements():
global maxelement
#a = driver.find_elements(By.CLASS_NAME, "k-link")
classname = (By.CLASS_NAME, "k-link")
a = WebDriverWait(driver, 120).until(EC.visibility_of_all_elements_located(classname))
print(a)
for x in range(maxelement):
selector = "li.k-item:nth-child(" + str(x) + ") > span:nth-child(2)"
print(selector)
xpathvar = "/html/body/div[4]/section[2]/div/div[1]/div/div/ul/li[" + str(x) + "]/span[2]"
print(xpathvar)
print('***************')
# First table Logic
time.sleep(60)
## Lo puse asi PAra provar la logica y esta perfecta corre muy rapido y bien.
try:
print('Entro al Try del Tabulador')
first_tab = driver.find_element(By.CSS_SELECTOR, selector)
first_tab.click()
click = True
except NoSuchElementException:
click = False
pass
#print(str(x) + 'Tab not Found')
time.sleep(60)
if click == True:
try:
download_first = driver.find_element(By.XPATH, xpathvar)
download_first.click()
except NoSuchElementException:
click = False
pass
#print('Downloaded file Succesfully' + str(x))
#time.sleep(60)
print('Cycle ends correclty')
def elements():
global maxelement
#a = driver.find_elements(By.CLASS_NAME, "k-link")
classname = (By.CLASS_NAME, "k-link")
a = WebDriverWait(driver, 120).until(EC.visibility_of_all_elements_located(classname))
print(a)
for x in range(maxelement):
selector = "li.k-item:nth-child(" + str(x) + ") > span:nth-child(2)"
print(selector)
xpathvar = "/html/body/div[4]/section[2]/div/div[1]/div/div/ul/li[" + str(x) + "]/span[2]"
print(xpathvar)
print('***************')
# First table Logic
time.sleep(60)
## Lo puse asi PAra provar la logica y esta perfecta corre muy rapido y bien.
try:
print('Entro al Try del Tabulador')
first_tab = driver.find_element(By.CSS_SELECTOR, selector)
first_tab.click()
click = True
except NoSuchElementException:
click = False
pass
#print(str(x) + 'Tab not Found')
time.sleep(60)
if click == True:
try:
download_first = driver.find_element(By.XPATH, xpathvar)
download_first.click()
except NoSuchElementException:
click = False
pass
#print('Downloaded file Succesfully' + str(x))
#time.sleep(60)
print('Cycle ends correclty')

Cannot GeoCode with Tigris

I'm trying to generate census tracts geoids for a batch of addresses. When I use the "append_geoid" function in the tigris package, r returns "Error in call_geolocator(as.character(address$street[i]), as.character(address$city[i]), : Bad Request (HTTP 400)".
I used the example data given in the r documentation and it produced the same result. Code below. Any help on how to solve the issue is appreciated!
airports <- dplyr::data_frame(street = "700 Catalina Dr", city = "Daytona Beach", state = "FL")
append_geoid(airports, 'tr) # Populate Census Tract GEOID
EDIT: A fixed version of the package is on github:
remotes::install_github("walkerke/tigris")
Then try again
EDIT 2:
The version on github still seems to give errors, though different ones this time. The HTTP call succeeds, but the response doesn't contain what his function expects it to. I'd contact him or her.
My Initial Post:
I got the same message as you do.
I did: debug( call_geolocator )
And ran it again, this time stepping through it. After a few code lines it creates the url: https://geocoding.geo.census.gov/geocoder/geographies/address?street=700%20Catalina%20Dr&city=Daytona%20Beach&state=FL&benchmark=Public_AR_Census2010&vintage=Census2010_Census2010&layers=14&format=json
This url then fails. Opening this url in a browser also gives an error, saying invalid benchmark.
At this point it's about time to call the author and make him aware that his package is not working any more.
For reference, this is what the debug session looked like in my terminal, until I inspected the full url created and hit Q to stop debuging:
> debug( call_geolocator )
> append_geoid(airports, 'tract') # Populate Census Tract GEOID
debugging in: call_geolocator(as.character(address$street[i]), as.character(address$city[i]),
as.character(address$state[i]))
debug: {
call_start <- "https://geocoding.geo.census.gov/geocoder/geographies/address?"
if (is.na(zip)) {
url <- paste0("street=", utils::URLencode(street), "&city=",
utils::URLencode(city), "&state=", state)
}
if (!is.na(zip)) {
if (class(zip) == "character" & nchar(zip) == 5 & !grepl("\\D",
zip)) {
url <- paste0("street=", utils::URLencode(street),
"&city=", utils::URLencode(city), "&state=",
state, "&zip=", zip)
}
else {
message("'zip' (", paste0(zip), ") was not a 5-character-long string composed of :digits:. Using only street, city, state.")
url <- paste0("street=", utils::URLencode(street),
"&city=", utils::URLencode(city), "&state=",
state)
}
}
call_end <- "&benchmark=Public_AR_Census2010&vintage=Census2010_Census2010&layers=14&format=json"
url_full <- paste0(call_start, url, call_end)
r <- httr::GET(url_full)
httr::stop_for_status(r)
response <- httr::content(r)
if (length(response$result$addressMatches) == 0) {
message(paste0("Address (", street, " ", city, " ", state,
") returned no address matches. An NA was returned."))
return(NA_character_)
}
else {
if (length(response$result$addressMatches) > 1) {
message(paste0("Address (", street, " ", city, " ",
state, ") returned more than one address match. The first match was returned."))
}
return(response$result$addressMatches[[1]]$geographies$`Census Blocks`[[1]]$GEOID)
}
}
Browse[2]>
debug: call_start <- "https://geocoding.geo.census.gov/geocoder/geographies/address?"
Browse[2]>
debug: if (is.na(zip)) {
url <- paste0("street=", utils::URLencode(street), "&city=",
utils::URLencode(city), "&state=", state)
}
Browse[2]>
debug: url <- paste0("street=", utils::URLencode(street), "&city=",
utils::URLencode(city), "&state=", state)
Browse[2]>
debug: if (!is.na(zip)) {
if (class(zip) == "character" & nchar(zip) == 5 & !grepl("\\D",
zip)) {
url <- paste0("street=", utils::URLencode(street), "&city=",
utils::URLencode(city), "&state=", state, "&zip=",
zip)
}
else {
message("'zip' (", paste0(zip), ") was not a 5-character-long string composed of :digits:. Using only street, city, state.")
url <- paste0("street=", utils::URLencode(street), "&city=",
utils::URLencode(city), "&state=", state)
}
}
Browse[2]>
debug: call_end <- "&benchmark=Public_AR_Census2010&vintage=Census2010_Census2010&layers=14&format=json"
Browse[2]>
debug: url_full <- paste0(call_start, url, call_end)
Browse[2]>
debug: r <- httr::GET(url_full)
Browse[2]> url_full
[1] "https://geocoding.geo.census.gov/geocoder/geographies/address?street=700%20Catalina%20Dr&city=Daytona%20Beach&state=FL&benchmark=Public_AR_Census2010&vintage=Census2010_Census2010&layers=14&format=json"
Browse[2]> Q
Going to the human interface of this: https://geocoding.geo.census.gov/geocoder/locations/address?form
It does indeed look like the benchmark in that url above is no longer an available in the dropdown select box. Changing it to Public_AR_Census2020 instead gives another error, Invalid vintage in request. Changing 2010 to 2020 in that string results in a successfull HTTP request: https://geocoding.geo.census.gov/geocoder/geographies/address?street=700%20Catalina%20Dr&city=Daytona%20Beach&state=FL&benchmark=Public_AR_Census2020&vintage=Census2010_Census2010&layers=14&format=json .
This doesn't really help you much at this point, but at least you can contact the author with an indication that the problem can be solved and you could give him some info to start working with.
If you're savy, you could clone his package source and fix it yourself, offer the fix to him, but nevertheless use your own fixed package until he gets around.

reading latex accents of .bib in R

When I export .bib references with accents coded in latex (as they are exported from mendeley, for example), then they don't look as expected for further independent processing in R.
myfile.bib:
#misc{Llorens1980,
abstract = {Aunque el reactor de fusi{\'{o}}n termonuclear constituye la esperanza m{\'{a}}s s{\'{o}}lida de obtenci{\'{o}}n de energ{\'{i}}a a gran escala, los problemas f{\'{i}}sicos y tecnol{\'{o}}gicos que el mismo plantea son muchos y dif{\'{i}}ciles.},
author = {Llorens, Mart{\'{i}}n and Menzell, Alfred and Villarrubia, Miguel},
booktitle = {Investigaci{\'{o}}n y Ciencia (Scientific American)},
keywords = {INGENIER{\'{I}}A NUCLEAR},
number = {51},
pages = {1--5},
title = {{F{\'{i}}sica y tecnolog{\'{i}}a del reactor de fusi{\'{o}}n}},
volume = {DICIEMBRE},
year = {1980}
}
In R:
testbibR <- RefManageR::ReadBib("myfile.bib")
testbibR$author
[1] "Mart\\'in Llorens" "Alfred Menzell" "Miguel Villarrubia"
testbibR$title
[1] "{F{\\'{i}}sica y tecnolog{\\'{i}}a del reactor de fusi{\\'{o}}n}"
btex<-bibtex::read.bib("myfile.bib")
btex$author
[1] "Mart\\'in Llorens" "Alfred Menzell" "Miguel Villarrubia"
btex$title
[1] "{F{\\'{i}}sica y tecnolog{\\'{i}}a del reactor de fusi{\\'{o}}n}"
testbib <- bib2df::bib2df("myfile.bib")
testbib$AUTHOR[[1]]
[1] "Llorens, Mart{\\'{i}}n" "Menzell, Alfred" "Villarrubia, Miguel"
testbib$TITLE
[1] "F{\\'{i}}sica y tecnolog{\\'{i}}a del reactor de fusi{\\'{o}}n"
I wonder if I can see a Martín in those places
Related post: https://github.com/ropensci/bib2df/issues/35
By the way, when importing / exporting those bibs, packages seem to rewrite in (other) latex format, the author field (Mart\'in). Only bib2df writes all fields as the original, see above.
RefManageR::WriteBib(testbibR,"refmanager.bib")
bibtex::write.bib(btex,"bibtex.bib")
bib2df::df2bib(testbib,"bib2df")
This is a workaround to remove some latex accents from .bib.
As I based this answer in this post' answer, the first part is in python.
python: Dictionary to .csv
latexAccents = [
[ u"Í", "{\\'{I}}"],
[ u"í", "{\\'{i}}"],
[ u"á", "{\\'{a}}"],
[ u"é", "{\\'{e}}"],
[ u"ó", "{\\'{o}}"],
[ u"ú", "{\\'{u}}"],
]
import pandas
mydf = pandas.DataFrame(latexAccents)
newname = "dictaccent.csv"
mydf.to_csv(newname, index =False)
R: Replace latex in .bib
dictaccent <- read.csv("dictaccent.csv")
bibLines <- readLines("myfile.bib")
library(stringi)
for (i in 1:nrow(dictaccent)){
for (j in 1:length(bibLines)) {
bibLines[j]<-stri_replace_all_fixed(bibLines[j], dictaccent$X1[i], dictaccent$X0[i])
}
}
writeLines(bibLines,"noLatex.bib")
commented in other post

Problems with scan() function in R

I am trying to do a simple process to get values from console with scan()
function in R.
The above R code works well:
funent <- function(){
val <- scan(,,1)
return(as.character(val))
}
print("Seleccione: 1. consulta, 2.cirugia")
tipo <- funent()
But when I add more code below it doesn't work. The execution doesn't stop in scan.
funent <- function(){
val <- scan(,,1)
return(as.character(val))
}
print("Seleccione: 1. consulta, 2.cirugia")
tipo <- funent()
while((tipo < 1 | tipo >2 )){
if (tipo < 1 | tipo >2 ) {
print("Introduzca 1(consulta) o 2(cirugia)")
tipo <- funent()
}
}
Is there anything wrong in my R code?
Nothing is wrong with your code. The execution doesn't stop in scan because the value of tipo is 1 or 2. It works as expected when tipo is outside that range:
tipo = 0
while((tipo < 1 | tipo >2 )){
if (tipo < 1 | tipo >2 ) {
print("Introduzca 1(consulta) o 2(cirugia)")
tipo <- funent()
}
}
[1] "Introduzca 1(consulta) o 2(cirugia)"
1:

Resources