r - dplyr::mutate 是否适用于记录样式的列?
问题描述
我最近一直在测试 vctrs 包,尤其是最近他们所谓的“记录样式”对象,我想知道是否有任何方法可以让它们与 dplyr::mutate 配合得很好。目前,当 dplyr::mutate 在我尝试使用对象时给我一个关于对象长度的错误。
我不知道合适的内置类型,所以作为一个代表,我将使用这个小插图中描述的理性类。
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"
map
因此,我们可以使用或as.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
推荐阅读
- javascript - 删除所有包含相同键且至少有一个值为 true 的对象数组
- python - Tkinter GUI:添加图像并更改颜色
- node.js - 如何在 NodeJS 和 Mongodb 中存储多个个人资料图片?
- angular - 如果页面的图像仍在加载,离子/角度模态控制器模态将不会打开
- api - 带有后端 API 和新 B2B API 的 SPA - 如何部署
- python - python中的数字序列
- python - Yocto QtCore/QtCoremod.sip 未找到
- javascript - nodemon server.js 在 vs 代码中执行
- opencv - 不同光照条件下透明瓶中颜色的识别
- php - 如何让用户在注销后不返回仪表板?