Quantcast
Channel: Active questions tagged r - Stack Overflow
Viewing all articles
Browse latest Browse all 201945

Does dplyr::mutate work with record-style columns?

$
0
0

I've been testing out the vctrs package recently, especially what they call "record-style" objects recently, and I'm wondering if there's any way to get them to play nice with dplyr::mutate. Currently, when dplyr::mutate gives me an error about the length of the objects whenever I try to use them.

I don't know of a built in type that's appropriate, so as a reprex I'm going to use the rational class described in this vignette.

library("vctrs")
library("dplyr")
new_rational <- function(n = integer(), d = integer()) {
  vec_assert(n, ptype = integer())
  vec_assert(d, ptype = integer())

  new_rcrd(list(n = n, d = d), class = "vctrs_rational")
}

format.vctrs_rational <- function(x, ...) {
  n <- field(x, "n")
  d <- field(x, "d")

  out <- paste0(n, "/", d)
  out[is.na(n) | is.na(d)] <- NA

  out
}

So far so good, but when I try to create a column of rationals using dplyr::mutate I get an error

df <- data.frame(n = c(1L, 2L, 3L), d = 2L)
df %>% dplyr::mutate(frac = new_rational(n, d))
#> Error: Column `frac` must be length 3 (the number of rows) or one, not 2

But creating the column in base R works just fine:

df$rational <- new_rational(df$n, df$d)
df
#>   n d rational
#> 1 1 2      1/2
#> 2 2 2      2/2
#> 3 3 2      3/2

Is there some trick to get this to work using dplyr::mutate, or is this just not possible?


Viewing all articles
Browse latest Browse all 201945

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>