gpt4 book ai didi

r - 加速分位数计算

转载 作者:行者123 更新时间:2023-12-01 10:51:01 25 4
gpt4 key购买 nike

我正在使用 Hmisc用于计算两个连续变量的分位数并在交叉表中比较结果的包。你在下面找到我的代码。

我的问题是,如果观察次数增加,分位数的计算需要相当长的时间。

是否有可能通过使用 data.table 来加快此过程? , ddply或任何其他包?

谢谢。

library(Hmisc)

# Set seed
set.seed(123)

# Generate some data
a <- sample(1:25, 1e7, replace=TRUE)
b <- sample(1:25, 1e7, replace=TRUE)
c <- data.frame(a,b)

# Calculate quantiles
c$a.quantile <- cut2(a, g=5)
c$b.quantile <- cut2(b, g=5)

# Output some descriptives
summaryM(a.quantile ~ b.quantile, data=c, overall=TRUE)

# Time spent for calculation:
# User System verstrichen
# 25.13 3.47 28.73

最佳答案

正如 jlhoward 和 Ricardo Saporta 所述 data.table在这种情况下,似乎并没有加快速度。 cut2功能显然是这里的瓶颈。我使用另一个函数来计算分位数(参见 Is there a better way to create quantile "dummies" / factors in R? )并且能够将计算时间减少一半:

qcut <- function(x, n) {
if(n<=2)
{
stop("The sample must be split in at least 3 parts.")
}
else{
break.values <- quantile(x, seq(0, 1, length = n + 1), type = 7)
break.labels <- c(
paste0(">=",break.values[1], " & <=", break.values[2]),
sapply(break.values[3:(n)], function(x){paste0(">",break.values[which(break.values == x)-1], " & <=", x)}),
paste0(">",break.values[(n)], " & <=", break.values[(n+1)]))
cut(x, break.values, labels = break.labels,include.lowest = TRUE)
}
}

c$a.quantile.2 <- qcut(c$a, 5)
c$b.quantile.2 <- qcut(c$b, 5)
summaryM(a.quantile.2 ~ b.quantile.2, data=c, overall=TRUE)

# Time spent for calculation:
# User System verstrichen
# 10.22 1.47 11.70

使用 data.table将计算时间再减少一秒,但我喜欢 Hmisc 的总结包更好。

关于r - 加速分位数计算,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20333268/

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