r语言 - dplyr::mutate 是否适用于记录样式列?



我最近一直在测试vctrs包,特别是他们最近所谓的"记录式"对象,我想知道是否有任何方法可以让它们与dplyr::mutate很好地配合使用。目前,每当我尝试使用对象时,dplyr::mutate 都会给我一个关于对象长度的错误。

我不知道合适的内置类型,因此作为 reprex,我将使用此小插曲中描述的理性类。

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
}

到目前为止一切顺利,但是当我尝试使用 dplyr::mutate 创建一列有理数时,我收到一个错误

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

但是在基本 R 中创建列就可以了:

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

是否有一些技巧可以使用dplyr::mutate使其工作,或者这是不可能的?

new_rational

以列表格式返回输出,如下所示

> typeof(new_rational(n=1L, d=2L))
[1] "list"

因此,我们可以使用mapas.list"@Ronak的建议"然后使用unnest将输出作为列表获取。

df %>% dplyr::mutate(frac = purrr::map2(n,d, ~new_rational(.x, .y))) %>% 
tidyr::unnest(cols=c(frac))
# A tibble: 3 x 3
n     d       frac
<int> <int> <vctrs_rt>
1     1     2        1/2
2     2     2        2/2
3     3     2        3/2

从 vctrs 0.3.6/R 4.0.3 开始,您的 reprex 按预期工作:

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
}
df <- data.frame(n = c(1L, 2L, 3L), d = 2L)
df %>% dplyr::mutate(frac = new_rational(n, d))
#>   n d frac
#> 1 1 2  1/2
#> 2 2 2  2/2
#> 3 3 2  3/2

创建于 2021-02-03 由 reprex 软件包 (v0.3.0(

最新更新