Get the single value
Description
This raises an error if there is not exactly one value.
Usage
<Expr>$item(..., allow_empty = FALSE)
Arguments
…
|
These dots are for future extensions and must be empty. |
allow_empty
|
Allow having no values to return null.
|
Value
A polars expression
See Also
$get() to get a single value by index.
Examples
library("polars")
# This function may be useful to force ourselves to handle cases where we
# expect a single value but there are several. For example, we might expect
# `$mode()` to return a single value...
df <- pl$DataFrame(x = c("a", "a", "c"))
df$select(
mode = pl$col("x")$mode()$item()
)
#> shape: (1, 1)
#> ┌──────┐
#> │ mode │
#> │ --- │
#> │ str │
#> ╞══════╡
#> │ a │
#> └──────┘
# ... but this is not always the case:
df <- pl$DataFrame(x = c("a", "b", "c"))
tryCatch(
{
df$select(
mode = pl$col("x")$mode()$item()
)
},
error = function(e) print(e)
)
#> <error/rlang_error>
#> Error in `df$select()`:
#> ! Evaluation failed in `$select()`.
#> Caused by error:
#> ! Evaluation failed in `$collect()`.
#> Caused by error:
#> ! aggregation 'item' expected a single value, got 3 values
#> ---
#> Backtrace:
#> ▆
#> 1. ├─base::tryCatch(...)
#> 2. │ └─base (local) tryCatchList(expr, classes, parentenv, handlers)
#> 3. │ └─base (local) tryCatchOne(expr, names, parentenv, handlers[[1L]])
#> 4. │ └─base (local) doTryCatch(return(expr), name, parentenv, handler)
#> 5. └─df$select(mode = pl$col("x")$mode()$item())
#> 6. ├─polars:::wrap(self$lazy()$select(...)$collect(optimizations = DEFAULT_EAGER_OPT_FLAGS)) at r-polars/R/dataframe-frame.R:367:3
#> 7. │ └─rlang::try_fetch(...) at r-polars/R/utils-wrap.R:3:3
#> 8. │ ├─base::tryCatch(...)
#> 9. │ │ └─base (local) tryCatchList(expr, classes, parentenv, handlers)
#> 10. │ │ └─base (local) tryCatchOne(expr, names, parentenv, handlers[[1L]])
#> 11. │ │ └─base (local) doTryCatch(return(expr), name, parentenv, handler)
#> 12. │ └─base::withCallingHandlers(...)
#> 13. └─self$lazy()$select(...)$collect(optimizations = DEFAULT_EAGER_OPT_FLAGS) at r-polars/R/utils-wrap.R:3:3
#> 14. ├─polars:::wrap(...) at r-polars/R/lazyframe-frame.R:308:3
#> 15. │ └─rlang::try_fetch(...) at r-polars/R/utils-wrap.R:3:3
#> 16. │ ├─base::tryCatch(...)
#> 17. │ │ └─base (local) tryCatchList(expr, classes, parentenv, handlers)
#> 18. │ │ └─base (local) tryCatchOne(expr, names, parentenv, handlers[[1L]])
#> 19. │ │ └─base (local) doTryCatch(return(expr), name, parentenv, handler)
#> 20. │ └─base::withCallingHandlers(...)
#> 21. └─ldf$collect(engine) at r-polars/R/lazyframe-frame.R:329:5
#> 22. └─polars:::.savvy_wrap_PlRDataFrame(...) at r-polars/R/000-wrappers.R:3861:5