gpt4 book ai didi

r - data.table 在 rbind, R 后丢失因子排序

转载 作者:行者123 更新时间:2023-12-04 18:08:52 27 4
gpt4 key购买 nike

rbind ing 二 data.table对于有序因素,排序似乎丢失了:

dtb1 = data.table(id = factor(c("a", "b"), levels = c("a", "c", "b"), ordered=T), key="id")
dtb2 = data.table(id = factor(c("c"), levels = c("a", "c", "b"), ordered=T), key="id")
test = rbind(dtb1, dtb2)
is.ordered(test$id)
#[1] FALSE

有什么想法或想法吗?

最佳答案

data.table做了一些花哨的步法,这意味着 data.table:::.rbind.data.tablerbind 时调用在对象上调用,包括 data.tables . .rbind.data.table利用与 rbindlist 相关的加速,通过一些额外的检查来匹配名称等。
.rbind.data.table使用 c 处理因子列将它们组合起来(因此保留了 levels 属性)

# the relevant code is
l = lapply(seq_along(allargs[[1L]]), function(i) do.call("c",
lapply(allargs, "[[", i)))

base R使用 c以这种方式不保留“有序”属性,它甚至不返回一个因素!

例如(在 base R 中)
f <- factor(1:2, levels = 2:1, ordered=TRUE)
g <- factor(1:2, levels = 2:1, ordered=TRUE)
# it isn't ordered!
is.ordered(c(f,g))
# [1] FALSE
# no suprise as it isn't even a factor!
is.factor(c(f,g))
# [1] FALSE

然而 data.table有一个 S3 方法 c.factor ,用于确保返回因子并保留水平。不幸的是,此方法不保留ordered 属性。
getAnywhere('c.factor')
# A single object matching ‘c.factor’ was found
# It was found in the following places
# namespace:data.table
# with value
#
# function (...)
# {
# args <- list(...)
# for (i in seq_along(args)) if (!is.factor(args[[i]]))
# args[[i]] = as.factor(args[[i]])
# newlevels = unique(unlist(lapply(args, levels), recursive = TRUE,
# use.names = TRUE))
# ind <- fastorder(list(newlevels))
# newlevels <- newlevels[ind]
# nm <- names(unlist(args, recursive = TRUE, use.names = TRUE))
# ans = unlist(lapply(args, function(x) {
# m = match(levels(x), newlevels)
# m[as.integer(x)]
# }))
structure(ans, levels = newlevels, names = nm, class = "factor")
}
<bytecode: 0x073f7f70>
<environment: namespace:data.table

所以是的,这是一个错误。现在报告为 #5019 .

关于r - data.table 在 rbind, R 后丢失因子排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19579223/

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