gpt4 book ai didi

r - 在 R 中使用 data.table 时返回错误的中位数

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

我有以下数据集

> head(DT)
V1 V2 V3 V4 V5 V6 V7
1: 2 1 2 0.91 0.02 880.00 1
2: 3 2 1 0.02 0.00 2.24 2
3: 1 1 1 0.15 0.01 3.41 3
4: 1 2 1 3.92 0.05 268.67 2
5: 1 1 2 0.10 0.01 1.59 3
6: 0 1 1 1.20 0.04 1.43 3

> sapply(DT, class)
V1 V2 V3 V4 V5 V6 V7
"integer" "integer" "integer" "numeric" "numeric" "numeric" "factor"

它扩展了数千行。我正在尝试计算因子变量 V7 定义的 8 个组内 V1-V6 的中值
> levels(DT$V7)
[1] "1" "2" "3" "4" "5" "6" "7" "8"

目前我正在使用以下命令,该命令返回错误:
> DT[, lapply(.SD, median), by = V7]
Error in `[.data.table`(DF, , lapply(.SD, median), by = V7) :
Column 1 of result for group 4 is type 'integer' but expecting type 'double'. Column types must be consistent for each group.

我在某处读到,解决这个问题的方法是使用 as.double(median(X)) .但这适用于单个列: DT[, as.double(median(X)), by = V7] ,但不适用于考虑所有列: DT[, lapply(.SD, as.double(median)), by = V7] (正如预期的那样,因为您必须将输入传递给中值)

我可以通过使用聚合来绕过
> aggregate(DT[,c(1:6), with = FALSE], by = list(DF$V7), FUN = median)
Group.1 V1 V2 V3 V4 V5 V6
1 1 0 1 1 1.285 0.04 401.500
2 2 1 2 1 3.565 0.06 6.400
3 3 0 1 1 0.360 0.03 11.200
4 4 1 1 1 74.290 0.26 325.960
5 5 2 1 0 1.145 0.04 1.415
6 6 0 1 1 10.100 0.18 93.000
7 7 1 1 0 0.740 0.04 1.080
8 8 1 1 0 7.970 0.40 0.050

但我想知道是否有办法解决上述错误并使用 data.table 进行此计算

最佳答案

median是不寻常的,因为它可以为相同的输入类型返回不同类型的返回值:

The default method returns a length-one object of the same type as x, except when x is integer of even length, when the result will be double.



但是,data.table 需要一致的返回值类型。你有两种可能:

将所有列转换为数字:
DT[, paste0("V", 1:6) := lapply(.SD, as.numeric), by = V7]

或者转换 median的返回值:
DT[, lapply(.SD, function(x) as.numeric(median(x))), by = V7]

关于r - 在 R 中使用 data.table 时返回错误的中位数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26401116/

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