Error: <text>:1:24: unexpected '{'
1: my_func <- fucntion(x) {
^
Michael Jones
29 November 2022
Code someone else has written
Code you write
Can you work differently to avoid errors in the first place?
ctrl + shift + F10
Error in df$Petal.Length: object of type 'closure' is not subsettable
df()
$
subsets dataTidyverse functions tend to be clear:
Error in `select()`:
! Can't subset columns that don't exist.
✖ Column `test` doesn't exist.
<error/rlang_error>
Error:
! object 'test' not found
---
Backtrace:
1. iris %>% pull(test)
9. base::.handleSimpleError(...)
10. rlang (local) h(simpleError(msg, call))
11. handlers[[1L]](cnd)
Run `rlang::last_trace()` to see the full context.
function (.data, ...)
{
UseMethod("select")
}
<bytecode: 0x557bd7e750f8>
<environment: namespace:dplyr>
function (.data, ...)
{
error_call <- dplyr_error_call()
loc <- tidyselect_fix_call(tidyselect::eval_select(expr(c(...)),
.data), call = error_call)
loc <- ensure_group_vars(loc, .data, notify = TRUE)
dplyr_col_select(.data, loc, names(loc))
}
<bytecode: 0x557bd93ee938>
<environment: namespace:dplyr>
Ensure you’re using code you expect:
filter()
before loading {dplyr} means you’re using base::filter()
Crash execution using stop()
, warn using warning()
Or using {cli} for richer, clearer messages.
loud_cli <- function(x) {
if (x == 4) {
cli::cli_abort(
message = c("Error in `loud_cli()`",
"x" = "This function can't have certain values",
"i" = "You gave it 4, don't do that again")
)
}
}
loud_cli(4)
Error in `loud_cli()`:
! Error in `loud_cli()`
✖ This function can't have certain values
ℹ You gave it 4, don't do that again
debug()
, debugonce()
and friendsdebugonce()
browser()
recover()
and trace()
(mostly rely on RStudio GUI)print()
Stop early if things are wrong
If you know what to do with errors, you can handle them automatically:
Just value
: signifying successNothing
: signifying failuretryCatch
debug()
is a very powerful tool