gpt4 book ai didi

r - 每列不同的硬阈值

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

我想对我的矩阵进行硬阈值处理,以便将低于某个数字的所有值都设置为零。但是,我希望该阈值因列而异(即每列都有自己的阈值)。我怎样才能在 R 中做到这一点?

这是简单的设置:

set.seed(1)
A <- matrix(runif(n = 12),nrow = 4)
# [,1] [,2] [,3]
#[1,] 0.2655087 0.2016819 0.62911404
#[2,] 0.3721239 0.8983897 0.06178627
#[3,] 0.5728534 0.9446753 0.20597457
#[4,] 0.9082078 0.6607978 0.17655675



threshholds <- c(0.3,1,0.5)

#wanted result:

# [,1] [,2] [,3]
#[1,] 0 0 0.62911404
#[2,] 0.3721239 0 0
#[3,] 0.5728534 0 0
#[4,] 0.9082078 0 0

我需要将它应用于大型矩阵,因此效率是相关的。

编辑:
收到了几个很好的建议,我比较了它们的速度以供将来引用:
set.seed(1)
A <- matrix(runif(n = 1E4*2E3),nrow = 2E3)

threshholds <- runif(n=1E4)

> system.time(A * (A > threshholds[col(A)]))# akrun
user system elapsed
0.394 0.124 0.519
> system.time(replace(A, A <= threshholds[col(A)], 0)) # akrun
user system elapsed
0.465 0.138 0.604
> system.time(pmin(A, A > threshholds[col(A)])) #akrun
user system elapsed
0.678 0.290 1.024
> system.time(A[t(apply(A, 1, `<`, threshholds))] <- 0) #Andrew Gustar
user system elapsed
0.875 0.306 1.200
> system.time(At <- apply(A, 1, applythresh)) + system.time(t(At)) #Chris Litter
user system elapsed
0.891 0.372 1.286
> system.time(sweep(A, 2, threshholds, function(a,b) {ifelse(a<b,0,a)})) #MrFlick
user system elapsed
1.752 0.598 2.354

最佳答案

这是一个矢量化选项

replace(A, A <= threshholds[col(A)], 0)

或者用一些算术
A * (A > threshholds[col(A)])
# [,1] [,2] [,3]
#[1,] 0.0000000 0 0.629114
#[2,] 0.3721239 0 0.000000
#[3,] 0.5728534 0 0.000000
#[4,] 0.9082078 0 0.000000

或与 pmin
pmin(A, A > threshholds[col(A)])
# [,1] [,2] [,3]
#[1,] 0.0000000 0 0.629114
#[2,] 0.3721239 0 0.000000
#[3,] 0.5728534 0 0.000000
#[4,] 0.9082078 0 0.000000

关于r - 每列不同的硬阈值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50881398/

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