R ';离散化';连续变量-但不是';因式分解';信息技术

R ';离散化';连续变量-但不是';因式分解';信息技术,r,simulation,R,Simulation,我正在尝试运行蒙特卡罗模拟,我想做的部分是重复一个过程,因为一个关键变量变得越来越“离散”(忽略“更离散”的概念基本上是没有意义的) 因此,如果xcut()可能适用于这些类型的工作,那么这里有一种使用sapply-循环的方法: #dummy data set.seed(1234) n = 1000 x <- rnorm(n) #Discretize a continuous variable z <- sapply(c(100,10,5,3), function(k){

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

因此,如果x
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])
#虚拟数据
种子集(1234)
n=1000

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

我会尝试:

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

首先,用下一个值计算
的每个值的平均值。然后将相应的平均值分配给
x
值所占用的区间。

这不会给出与OP的解相同的最小/最大值。
((points[-k]+points[-1])/2)[findInterval(x,points)]