我正在研究关于收入分配的项目...我想生成用于测试理论的随机数据。假设我有N = 5个国家,每个国家有1000个人口,我想为每个人口在每个人口中产生随机收入(正态分布),收入约束在0和1之间,并且具有相同的均值和不同的标准所有国家的偏差。我用函数rnorm(n,meanx,sd)来完成它。我知道UNIFORM DISTRIBUTION(runif(n,min,max))有一些设置min,max,但没有rnorm的参数,因为rnorm没有提供设置min和max值的参数,所以我必须写一段代码检查一组随机数据,看它们是否满足我[0,1]的约束条件在范围0和1内生成正态分布数据
我成功生成了n = 100的收入数据,但是如果我增加n = k的100次,例如,n = 200,300 ...... 1000,我的程序挂起了,我可以看到程序挂起的原因,因为它只是随机生成数据而没有min,max的限制因此,当我使用更大的n ,我将成功生成的概率小于n = 100,并且循环再次运行:生成数据,检查失败
从技术上讲,为了解决这个问题,我想把n = 1000分成小批量,比方说b = 100。由于rnorm成功生成范围为[0,1]范围内的100个样本,并且它是正态分布,所以如果我为100个样本的每个批次分别运行10次100个样本的循环,它将工作得很好。然后,我会将10 * 100个样本的所有数据收集到一个1000的数据中,供我以后分析。 然而,在数学上言语,我不确定n = 1000的正态分布的约束是否仍然满足或不这样做。我在这里附上我的代码。希望我的解释对你很清楚。所有的意见对我的工作都非常有用。非常感谢。
# Update:
# plot histogram
# create the random data with same mean, different standard deviation and x in range [0,1]
# Generate the output file
# Generate data for K countries
#---------------------------------------------
# Configurable variables
number_of_populations = 5
n=100 #number of residents (*** input the number whish is k times of 100)
meanx = 0.7
sd_constant = 0.1 # sd = sd_constant + j/50
min=0 #min income
max=1 #max income
#---------------------------------------------
batch =100 # divide the large number of residents into small batch of 100
x= matrix(
0, # the data elements
nrow=n, # number of rows
ncol=number_of_populations, # number of columns
byrow = TRUE) # fill matrix by rows
x_temp = rep(0,n)
# generate income data randomly for each country
for (j in 1:number_of_populations){
# 1. Generate uniform distribution
#x[,j] <- runif(n,min, max)
# 2. Generate Normal distribution
sd = sd_constant+j/50
repeat
{
{
x_temp <- rnorm(n, meanx, sd)
is_inside = TRUE
for (i in 1:n){
if (x_temp[i]<min || x_temp[i] >max) {
is_inside = FALSE
break
}
}
}
if(is_inside==TRUE) {break}
} #end repeat
x[,j] <- x_temp
}
# write in csv
# each column stores different income of its residents
working_dir= "D:\\dataset\\"
setwd(working_dir)
file_output = "random_income.csv"
sink(file_output)
write.table(x,file=file_output,sep=",", col.names = F, row.names = F)
sink()
file.show(file_output) #show the file in directory
#plot histogram of x for each population
#par(mfrow=c(3,3), oma=c(0,0,0,0,0))
attach(mtcars)
par(mfrow=c(1,5))
for (j in 1:number_of_populations)
{
#plot(X[,i],y,'xlab'=i)
hist(x[,j],main="Normal",'xlab'=j)
}
如果你想要一个正态分布,它不能像你描述的那样有界。你想要发生的值落在[0,1]之外? – Thomas
嗨,托马斯,我希望我的分析有效数据落在[0,1]。如果数据不符合约束,我根本无法使用它。 –
也许[此帖](http:// stackoverflow。com/questions/19343133/setting-upper-and-lower-limits-in-rnorm)帮助 –