生成四位数的1000个随机样本,并从数字总体中进行替换

问题描述 投票:0回答:2

[从数位(pop)中替换生成1000个4位随机样本。使用直方图绘制样本比例为1的分布。

我已经尝试过了,但是不相信这是正确的:

set.seed(123)

pop <- c(0,1,2,3,4,5,6,7,8,9)

y<-replicate(1000,sample(pop, size=4, replace = TRUE), simplify = FALSE)

d<-length(y) 

从向量x获得观测值1并将其存储在变量b中

e<-x[x==1]

存储在矢量x中的向量x存储在矢量c中的个数

f<-length(e)

求向量x中1的比例

prop<-f/d

prop

此外,我尝试使用此代码制作直方图,但由于某种原因它不会返回任何内容。有什么想法吗?

r random
2个回答
1
投票

我不完全确定这是否是您想要实现的目标,但我认为可能真的很接近。

library("purrr")

#Your population, vector with integers
pop <- 1:40
#get a vector of 1000 repetitions of sampling pop by 4 elements with replacement
df <- unlist(1:1000 %>%
    map(function(x) sample(pop,4,replace = T)))
#Get the proportion of ones in the df
prop <- length(df[df == 1]) / length(df)

#For example
#  0.02375

0
投票

您的代码实际上是正确的:

set.seed(123)
pop <- c(0,1,2,3,4,5,6,7,8,9)
y<-replicate(1000,sample(pop, size=4, replace = TRUE), simplify = FALSE)

这是一个列表,因为您指定simplify = FALSE,请执行以下操作:

class(y)
[1] "list"

您可以看到它的结构:

y[1:3]
[[1]]
[1] 2 2 9 1

[[2]]
[1] 5 4 3 5

[[3]]
[1] 8 9 4 2

如果要查找比例等,请取消列出您拥有的列表:

y = unlist(y)

对于1的比例,请执行:

mean(y==1)
[1] 0.09575

要获取直方图,请执行:

hist(y,col="steelblue",breaks=seq(-0.5,9.5,by=1))

enter image description here

在这种情况下,您需要指定休息时间,因为默认值是包括最左边的内容,这会让您感到很奇怪。或者在您的情况下,以下内容也不错:

barplot(table(y))

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.