【问题标题】:'Discretize' a continuous variable - but not 'factorize' it“离散化”一个连续变量 - 但不是“分解”它
【发布时间】:2015-06-02 07:50:40
【问题描述】:

我正在尝试运行蒙特卡罗模拟,我想做的一部分是重复一个过程,因为关键变量变得越来越“离散”(忽略“更离散”的想法基本上没有意义)。

因此,如果 x

例如,下面是丑陋(且效率低下)的双循环的样子:

    n = 1000
    x <- rnorm(n)
    k = 20
    points <- seq(from = min(x), to = max(x), length.out = k)
    for(i in 1:n){   
          for(j in 1:k){          
                if(x[i] < points[j]){
                      x[i] <- mean(c(points[j], points[j-1])) 
                      break
                }
          }      
    }

我尝试了“cut”,以及“apply”/“sapply”的多种不同变体,但没有什么能满足我的需求。上面的循环工作正常,但需要永远。如果我想模拟收敛等,这可能会运行数周,具体取决于设置。

任何关于我可能是什么的帮助

【问题讨论】:

    标签: r simulation


    【解决方案1】:

    对于这种工作,使用非常高效的findInterval

    我会尝试:

    ((points[-k]+points[-1])/2)[findInterval(x,points)]
    

    首先,您评估point 的每个值的平均值及其下一个值。然后将相应的平均值分配给x值占用的区间。

    【讨论】:

    • 这不会给出与 OP 解决方案相同的最小值/最大值。
    【解决方案2】:

    cut() 可能适用于这些类型的工作,但这里有一种使用sapply - 循环的方法:

    #dummy data
    set.seed(1234)
    n = 1000
    x <- rnorm(n)
    
    #Discretize a continuous variable
    z <- 
      sapply(c(100,10,5,3), function(k){
        sapply(1:length(x), function(i){
          points <- seq(from = min(x), to = max(x), length.out = k)
          mean(c(points[which(x[i]>points)][1],
               points[which(x[i]<points)][1]))
        })
      })
    
    #plot hist
    par(mfrow=c(2,2))
    hist(z[,1])
    hist(z[,2])
    hist(z[,3])
    hist(z[,4])
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-08-10
      • 1970-01-01
      • 1970-01-01
      • 2018-05-16
      • 1970-01-01
      • 1970-01-01
      • 2020-04-04
      • 1970-01-01
      相关资源
      最近更新 更多