如何使用“采样”包在 R 中创建分层样本?我的数据集有 355,000 个观察值。该代码直到最后一行都运行良好。下面是我编写的代码,但我总是收到以下消息:“sort.list(y) 中的错误:‘x’对于‘sort.list’必须是原子的,您在列表上调用了‘sort’吗?”
请不要向我指出 Stackoverflow 上的旧消息。我研究了它们,但未能使用它们。谢谢。
## lpdata file has 355,000 observations
# Exclude Puerto Rico, Virgin Islands and Guam
sub.lpdata<-subset(lpdata,"STATE" != 'PR' | "STATE" != 'VI' | "STATE" != 'GU')
## Create a 10% sample, stratified by STATE
sort.lpdata<-sub.lpdata[order(sub.lpdata$STATE),]
tab.state<-data.frame(table(sort.lpdata$STATE))
size.strata<-as.vector(round(ceiling(tab.state$Freq)*0.1))
s<-strata(sort.lpdata,stratanames=sort.lpdata$STATE,size=size.strata,method="srswor")}
最佳答案
去年我不得不做类似的事情。如果这是您经常做的事情,您可能需要使用如下所示的函数。此函数可让您指定要从中采样的数据框的名称、哪个变量是 ID 变量、哪个是分层,以及是否要使用“set.seed”。您可以将该函数另存为“stratified.R”之类的文件,并在需要时加载它。请参阅http://news.mrdwab.com/2011/05/20/stratified-random-sampling-in-r-from-a-data-frame/
stratified = function(df, group, size) {
# USE: * Specify your data frame and grouping variable (as column
# number) as the first two arguments.
# * Decide on your sample size. For a sample proportional to the
# population, enter "size" as a decimal. For an equal number
# of samples from each group, enter "size" as a whole number.
#
# Example 1: Sample 10% of each group from a data frame named "z",
# where the grouping variable is the fourth variable, use:
#
# > stratified(z, 4, .1)
#
# Example 2: Sample 5 observations from each group from a data frame
# named "z"; grouping variable is the third variable:
#
# > stratified(z, 3, 5)
#
require(sampling)
temp = df[order(df[group]),]
if (size < 1) {
size = ceiling(table(temp[group]) * size)
} else if (size >= 1) {
size = rep(size, times=length(table(temp[group])))
}
strat = strata(temp, stratanames = names(temp[group]),
size = size, method = "srswor")
(dsample = getdata(temp, strat))
}
关于r - 如何在 R 中按州创建分层样本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9703428/