R - Check if error message is due to missing arguments - r

I would like to check if an error message is due to missing arguments that have no default values. I'm not sure how to do this since such error messages don't appear to have a unique class or identifier that distinguishes them from other error messages.
I can check if the message contains the words 'no default', but this doesn't seem very robust:
res = try(mean(rm = T), silent = T)
grepl('no default', attr(res, "condition"))
[1] TRUE

Related

tdplyr - (TDR_E1001) using fastload

I am getting some weird errors, when I try to upload a data.frame to the Teradata database using td_fastload() in R.
The copy_to() method works for smaller sets without any issues, just takes a while... but td_fastload() for bigger sets don't work, here is what I am getting, what does this mean ?
my command is:
td_fastload(con, df = TEST55, table.name = "TEST55", overwrite = TRUE )
and the errors are:
Error: In value[[3L]](cond):
[tdplyr - (TDR_E1001)] Error: In value[[3L]](cond):
[tdplyr - (TDR_E1001)] Error in obtainRows(res, FALSE, params): Argument params class character differs from the required data.frame or list
In addition: Warning messages:
1: In td_fastload(con, df = TEST55, table.name = 'TEST55', overwrite = TRUE):
[tdplyr - (TDR_W1011)] Setting 'overwrite = TRUE' will drop existing table 'TEST55' and recreate it with new schema.
2: In sprintf(gettext(fmt, domain = domain, trim = trim), ...) :
one argument not used by format 'Error in obtainRows(res, FALSE, params): Argument params class character differs from the required data.frame or list
'
3: In sprintf(gettext(fmt, domain = domain, trim = trim), ...) :
one argument not used by format 'Error: In value[[3L]](cond):
[tdplyr - (TDR_E1001)] Error in obtainRows(res, FALSE, params): Argument params class character differs from the required data.frame or list```

Referencing a column in a table: $ operator is invalid for atomic vector

I am trying to run the following code
Newdata2 = df3%>%
mutate(unemployedempPopRatio = Unemployed * empPopRatio)
With homoskedastic error
fit4 = lm(Satisfaction~Unemployed+empPopRatio+unemployedempPopRatio,Newdata2)%>%
stargazer(header = FALSE, type = 'latex')
With cluster error
cls_err2 = cluster.vcov(fit4, Newdata2$country)
Y = coeftest(fit4,cls_err2)
stargazer(Y, header = FALSE, type = 'latex')
But I am getting an error message that says '$ operator is invalid for atomic vector'. I used the $ operator in the third last line. I checked the type of Newdata2 and it is a list. I am completely new to R and am not sure what went wrong. It would be great if someone could point it out. Thank you.

Meaning of this warning; "Warning message: In get(object, envir = currentEnv, inherits = TRUE) : restarting interrupted promise evaluation"

I have written a function in R which extracts data from a database and builds a new table.
My new table is labeled with the date of the extract (build_date_0).
When I'm debugging my function I get the following warning when I look at my date string:
Browse[2]> build_date_0
[1] "2019-05-01"
Warning message:
In get(object, envir = currentEnv, inherits = TRUE) :
restarting interrupted promise evaluation
Questions:
What does this warning mean / what is happening (step-by-step/basics)?
Should I care?
In general how can I find out more about this error?
This is my code:
build_account_db = function(conn = connection_object
,various_inputs = 24){
browser()
# create connection objects
tabs_1 = dplyr::tbl(conn,in_schema("DB_1","VIEW_W") # some table
# create date string
build_date_0 = lubridate::today() %>% as.character()
build_date = str_replace_all(build_date_0,"-+","_")
db_name_1 = paste0('DATABASE.tab_1_',build_date)
db_name_2 = paste0('DATABASE.tab_2_',build_date)
# build query
query_text_1 = tabs_1 %>% select(COL_1) # some query
query_text_1 = tabs_1 %>% select(COL_2)
# build new tables
create_db = DBI::dbSendQuery(conn_t,paste('CREATE TABLE',db_name_1,'AS (',query_text_1,') WITH DATA PRIMARY INDEX (ID_1)'))
create_db2 = DBI::dbSendQuery(conn_t,paste('CREATE TABLE',db_name_2,'AS (',query_text_2,') WITH DATA PRIMARY INDEX (ID_1)'))
}
When I check a variable, I may or may not get this warning (it varies, even if I restart R, and run my code again with a cleared environment)
Browse[2]> build_date
[1] "2019-02-28 11:00:00 AEDT"
Warning message:
In get(object, envir = currentEnv, inherits = TRUE) :
restarting interrupted promise evaluation
What I've tried: I read this question, but it's more about suppressing the error. Also, google.
I found this link on promises and evaluation in R helpful for a related problem: https://mailund.dk/posts/promises-and-lazy-evaluation/. I wonder if after build_date_0 = lubridate::today() %>% as.character() if you add a call to just build_date_0 if that would solve the promise? Good luck!

R - `try` in conjunction with capturing ALL console output?

Here's a piece of code I'm working with:
install.package('BiocManager');BiocManager::install('UniProt.ws')
requireNamespace('UniProt.ws')
uniprot_object <- UniProt.ws::UniProt.ws(
UniProt.ws::availableUniprotSpecies(
pattern = '^Homo sapiens$')$`taxon ID`)
query_results <- try(
UniProt.ws::select(
x = uniprot_object,
keys = 'BAA08084.1',
keytype = 'EMBL/GENBANK/DDBJ',
columns = c('ENSEMBL','UNIPROTKB')))
This particular key/keytype combination is non-productive and produces the following output:
Getting mapping data for BAA08084.1 ... and ACC
error while trying to retrieve data in chunk 1:
no lines available in input
continuing to try
Error in `colnames<-`(`*tmp*`, value = `*vtmp*`) :
attempt to set 'colnames' on an object with less than two dimensions
Of the two [eE]rrors reported only the second is a 'proper' R error object and given the use of try accordingly captured in the variable query_result.
I am, however, desperate to capture the other error bit (no lines available in input) to inform downstream programmatic processes.
After playing with a plethora of capture.output, sink, purrr::quietly, etc. options found by startpaging (googling), I continue to fail capturing that bit. How can I do that?
As #Csd suggested, you could use tryCatch. The message that you are after is printed by the message() function in R, not stop(), so try() will ignore it. To capture output from message(), use code like this:
query_results <- tryCatch(
UniProt.ws::select(
x = uniprot_object,
keys = 'BAA08084.1',
keytype = 'EMBL/GENBANK/DDBJ',
columns = c('ENSEMBL','UNIPROTKB')),
message = function(e) conditionMessage(e))
This will abort evaluation when it gets any message, and return the message in query_results. If you are doing more than debugging, you probably want the message saved, but evaluation to continue. In that case, use withCallingHandlers instead. For example,
saveMessages <- c()
query_results <- withCallingHandlers(
UniProt.ws::select(
x = uniprot_object,
keys = 'BAA08084.1',
keytype = 'EMBL/GENBANK/DDBJ',
columns = c('ENSEMBL','UNIPROTKB')),
message = function(e)
saveMessages <<- c(saveMessages, conditionMessage(e)))
When I run this version, query_results is unchanged (because the later error aborted execution), but the messages are saved:
saveMessages
[1] "Getting mapping data for BAA08084.1 ... and ACC\n"
[2] "error while trying to retrieve data in chunk 1:\n no lines available in input\ncontinuing to try\n"
Based on #user2554330 s most excellent answer, I constructed an ugly thing that does exactly what I want:
try to execute the statement
don't fail fatally
leave no ugly messages
allow me access to errors and messages
So here it is in all it's despicable glory:
saveMessages <- c()
query_results <- suppressMessages(
withCallingHandlers(
try(
UniProt.ws::select(
x = uniprot_object,
keys = 'BAA08084.1',
keytype = 'EMBL/GENBANK/DDBJ',
columns = c('ENSEMBL','UNIPROTKB')),
silent = TRUE),
message = function(e)
saveMessages <<- c(saveMessages, conditionMessage(e))))

Ignoring the symbol ° in R devtools function document()

I would like to create a package for internal usage (not to distribute somewhere). One of my functions contains the line
if (data$unit[i] != "°C") {
It works perfectly in the script, but if I want to create the documentation for my package using document() from devtools, i get the error
Error in parse(text = lines, keep.source = TRUE, srcfile = srcfilecopy(file, path_to_my_code: unexpected INCOMPLETE_STRING
279: if (! is.na(data$unit[i]){
280: if (data$unit[i] != "
addition: Warning message:
In readLines(con, warn = FALSE, n = n, ok = ok, skipNul = skipNul) :
invalid input found on input connection 'path_to_my_code'
If I delete the °-character, document() works. But I need this character there, so this is not an option.
When using double-\ in the if-clause, my function doesn't detect °C anymore as shown here:
test <- c("mg/l", "°C")
"\\°C" %in% test
[1] FALSE
If I use tryCatch, the documentation is also not created.
Replacing "°C" by gsub(pattern = '\\\\', replacement = "", x = '\\°C') causes the function to crash at the double-\ .
How can I tell document() that everything is fine and it should just create the files?

Resources