r-lib / rlang

Low-level API for programming with R
https://rlang.r-lib.org
Other
507 stars 139 forks source link

Suggestion for null coalescence operator #1583

Closed daniel-simeone closed 1 year ago

daniel-simeone commented 1 year ago

I couldn't help but notice the lovely little %|0|% operator (currently not exported) in operators.R (right after %||%)

  1. I'd vote for it to be exported - I love it.
  2. Here's an extension to extend it to work better for data frames with zero rows (but with non-zero columns):
`%|0|%` <- function(x, y) {
  if ("data.frame" %in% class(x)) {
    if(!nrow(x)) y else x
  } else{
    if (!length(x)) y else x
    }
}
lionel- commented 1 year ago

You can use vctrs::"%0%" for this. It supports empty data frames as well.

DanChaltiel commented 11 months ago

@lionel- This is actually a very useful feature for packages that import rlang. Moreover, I always expect rlang::`%||%` to behave that way, so IMHO they kind of belong together.

Could you consider re-exporting it? For most packages importing rlang, importing vctrs is quite an overkill.

lionel- commented 11 months ago

The problem is that rlang and vctrs are designed to be imported together, and the latter uses vec_is_empty() in its %0% implementation which rlang can't use.