gpt4 book ai didi

r - data.table 将 `by` 中的因子转换为基础整数?

转载 作者:行者123 更新时间:2023-12-04 10:54:07 24 4
gpt4 key购买 nike

考虑:

dt <- data.table(a=factor(rep(c("a", "b"), 5)), b=1:10)
dt[, list(mean(b), a), by=a]

产生:

   a V1 a
1: a 5 1
2: b 6 2

还有:

Classes 'data.table' and 'data.frame':  2 obs. of  3 variables:
$ a : Factor w/ 2 levels "a","b": 1 2
$ V1: num 5 6
$ a : int 1 2
- attr(*, ".internal.selfref")=<externalptr>

注意最后一列。实际的 by 列本身没有问题,当您尝试在 j 中显式地重新使用 by 列时,就会出现问题。我也相信 .BY 变量有同样的问题。这是在 1.9.2 中,在 Win 7 上使用 R 3.0.2 和 Rstudio(尽管在 Mac OS 10.8 上也观察到)。这曾经适用于早期版本(不确定哪个,从内存来看可能是错误的)。

如果我做了一些愚蠢的事情,请先在这里发帖。

此外,未分组的 by 变量似乎不再可用。例如:

dt[, list(mean(b), a[[2]]), by=a]

会产生越界错误,尽管情况可能总是如此。我本来希望 j 中的 adt 中得到完整的评估,所以 a[[2]] 应该工作(无论如何,在我的脑海里,也许它从来没有,也从来没有打算这样做)。

session 信息:

R version 3.0.2 (2013-09-25)
Platform: x86_64-pc-linux-gnu (64-bit)

locale:
[1] C

attached base packages:
[1] graphics grDevices utils datasets stats methods base

other attached packages:
[1] data.table_1.9.2

loaded via a namespace (and not attached):
[1] Rcpp_0.11.1 functional_0.4 plyr_1.8.1 reshape2_1.2.2
[5] stringr_0.6.2 tools_3.0.2

最佳答案

您的帖子中有三个问题。我会按顺序回答。

引用 j 中的因子列而不保留类已在 1.9.3 中修复(bug #5437 IIRC)。由于 1.9.0 中的各种增强功能(以及 R3.1.0 IIRC 的一些更改),这是一个微小的回归。现在也添加了测试来捕捉这一点。

require(data.table) ## 1.9.3
dt <- data.table(a=factor(rep(c("a", "b"), 5)), b=1:10)
str(dt[, list(mean(b), a), by=a])

# Classes ‘data.table’ and 'data.frame': 2 obs. of 3 variables:
# $ a : Factor w/ 2 levels "a","b": 1 2
# $ V1: num 5 6
# $ a : Factor w/ 2 levels "a","b": 1 2
# - attr(*, ".internal.selfref")=<externalptr>

.BY 的问题也已在 1.9.3 中修复:

dt[, print(.BY), by=a]
# $a
# [1] a
# Levels: a b

# $a
# [1] b
# Levels: a b

# Empty data.table (0 rows) of 1 col: a

dt[, list(mean(b), a[[2]]), by=a]
# Error in `[[.default`(a, 2) : subscript out of bounds

这是因为 by 中的变量/列在默认情况下可用作 length=1 向量。毕竟,这是您要分组的变量。

但是,我已经向@Matt 和@eddi 提出了此功能的潜在问题。你可以找到我和@eddi here 之间的简短讨论。评论下。我也写信给马特,目前正在讨论中。这将很快得到解决并记录在案,无论解决方案是什么。

我现在的立场是 by 中的列不应掩盖 dt 中的列。这从 bug #5191 开始,基本上是这样的:

DT <- data.table(x=1:5, y=6:10)
DT[, sum(x), by=x%%3L]
# x V1
# 1: 1 1
# 2: 2 2
# 3: 0 0

实际结果应该在哪里:

DT <- data.table(x=1:5, y=6:10)
DT[, sum(x), by=list(grp=x%%3L)]
# grp V1
# 1: 1 5
# 2: 2 7
# 3: 0 3

结果不正确,因为 byx 屏蔽了 DT 中的列 x 对应于每个团体。在这种情况下,发生这种情况是因为我们允许在 by 中使用表达式。

但是,即使情况并非如此,它也会扩展。考虑案例:

> DT[, sum(y), by=list(y=x)]
# y V1
# 1: 1 1
# 2: 2 2
# 3: 3 3
# 4: 4 4
# 5: 5 5

这里发生的事情是,按列命名 y 导致 DT 中的 y 被屏蔽。

恕我直言,应该做的是 by 不应该屏蔽 DT 中将在 j 中使用的列全部。相反,如果需要引用分组变量,他们应该使用已经存在的 .BY 变量(或者简单地使用 [1L] 对第一个索引进行子集化),如下所示:

> DT[, print(.BY$x), by=x]
# [1] 1
# [1] 2
# [1] 3
# [1] 4
# [1] 5
# Empty data.table (0 rows) of 1 col: x

这只是我的意见,可能还有其他理由支持保留当前功能并仅修复这些潜在的错误案例。我们必须讨论并解决这个问题,并根据我们得出的结论,相应地记录下来。

完成后我会更新这篇文章:)。

关于r - data.table 将 `by` 中的因子转换为基础整数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23366292/

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