gpt4 book ai didi

r - dplyr::mutate 中因素的奇怪回收 - 错误或功能?

转载 作者:行者123 更新时间:2023-12-04 17:00:05 24 4
gpt4 key购买 nike

函数mutate R 包中的“dplyr”对因子具有特殊的回收特性,因为它似乎返回因子 as.numeric .在以下示例中 y成为您所期望的,而 zc(1,1)

library(dplyr)
df <- data_frame(x=1:2)
glimpse(df %>% mutate(y="A", z=factor("B")))
# Variables:
# $ x (int) 1, 2
# $ y (chr) "A", "A"
# $ z (int) 1, 1

这背后有什么理由吗,还是一个错误?

(我使用 R 3.1.1 和 dplyr 0.3.0.1。)

编辑:

在 github 上将此作为问题发布后,Romain Francois 在数小时内修复了它!因此,如果上述问题存在,请使用 devtools::install_github获取最新版本:
library(devtools)
install_github("hadley/dplyr")

进而
library(dplyr)
df <- data_frame(x=1:2)
glimpse(df %>% mutate(y="A", z=factor("B")))
# Variables:
# $ x (int) 1, 2
# $ y (chr) "A", "A"
# $ z (fctr) B, B

干得好罗曼!

最佳答案

dplyr 使用 C++ 来执行实际 mutate手术。 Following the rabbit hole并注意到这是一个 ungrouped mutation ,我们可以使用我们值得信赖的调试器来注意以下几点。

debugonce(dplyr:::mutate_impl)
# Inside of mutate_impl we do:
class(dots[[2]]$expr) # which is a "call"!

所以现在我们知道了 lazy expression 的类型.我们 eval电话和 notice它是 supported type (不幸的是,R 的 TYPEOF 宏声明 factors are integers - 我们需要 Rf_isFactor 来区分)。

那么接下来会发生什么?我们 returned the result我们完成了。如果您尝试过 (df %>% mutate(y="A", z=factor(c("A","B"))))[[3]]已经,你会知道问题确实是回收。

Specifically ,C++ Gatherer object (其中 should really 正在检查 Rf_isFactor 以及它对 INTSXP s 的当前日期检查)正在使用 C++ 模板到 force a Vector<INTSXP> 要创建(隐式通过构造函数初始化 - 请注意 ConstantGathererImpl 中的 arity 2 调用)而不会记住结转因子“标签”。

TLDR:在 R 的 C++ 中,整数和因子在使用 TYPEOF 时具有相同的内部类型宏观和因素是一个奇怪的边缘情况。

随意向 dplyr 提交拉取请求,它正在积极开发中,hadley 和 Romain 是好人。你必须添加一个 if 语句 here .

关于r - dplyr::mutate 中因素的奇怪回收 - 错误或功能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26501795/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com