【问题标题】:Subset of data with replacement有替换的数据子集
【发布时间】:2012-06-14 15:07:32
【问题描述】:

我正在尝试从带有替换的数据中抽取一个子集,这里我展示了一个简单的示例,如下所示:

dat <- data.frame (
  group = c(1,1,2,2,2,3,3,4,4,4,4,5,5), 
  var = c(0.1,0.0,0.3,0.4,0.8,0.5,0.2,0.3,0.7,0.9,0.2,0.4,0.6)
) 

我只想根据组号对子集进行抽样。如果选择了组,例如 group = 1,则将选择整个组(在我上面的简单示例中为两个组成员)。如果该组被多次选择,则组号将更改为新组,例如 1.1、1.1、1.2、1.2、...。新数据可能如下所示:

newdat <- data.frame (
  group = c(3,3,5,5,3.1,3.1,1,1,3.2,3.2,5.1,5.1,3.3,3.3,2,2,2), 
  var = c(0.5,0.2,0.4,0.6,0.5,0.2,0.1,0.0,0.5,0.2,0.4,0.6,0.5,0.2,0.3,0.4,0.8)
) 

任何帮助将不胜感激。

【问题讨论】:

  • 我认为您的意思是带替换的样品?每个原始组应该有多少样本?
  • 对不起,我没有说新数据中的总样本量(组),比如说20。对于每个原始组,它可以随时(随机)选择。

标签: r


【解决方案1】:

这是一个相当简单的解决方案,它使用make.unique()newdat 中创建组的名称:

## Your data
dat <- data.frame (
  group = c(1,1,2,2,2,3,3,4,4,4,4,5,5), 
  var = c(0.1,0.0,0.3,0.4,0.8,0.5,0.2,0.3,0.7,0.9,0.2,0.4,0.6)
) 
n <- c(3,5,3,1,3,2,5,3,2)

## Make a 'look-up' data frame that associates sampled groups with new names,
## then use merge to create `newdat`
df <- data.frame(group = n, 
                 newgroup = as.numeric(make.unique(as.character(n))))
newdat <- merge(df, dat)[-1]
names(newdat)[1] <- "group"

【讨论】:

  • 是的。这很简单,新的组号没有问题。非常比你。
  • @gsk3 -- 没问题。它和make.names 不时对我有用(sometimes in surprising settings)。
【解决方案2】:

选择你喜欢的n

n <- 5 

然后运行它(或从中创建一个函数):

lvls <- unique(dat$group)
gp.orig <- gp.samp <- sample( lvls, n, replace=TRUE ) #this is the actual sampling
library(taRifx)
res <- stack.list(lapply( gp.samp, function(i) dat[dat$group==i,] ))
# Now make your pretty group names
while(any(duplicated(gp.samp))) {
  gp.samp[duplicated(gp.samp)] <- gp.samp[duplicated(gp.samp)] + .1
}
# Replace group with pretty group names (a simple merge doesn't work here because the groups are not unique)
gp.df <- as.data.frame(table(dat$group))
names(gp.df) <- c("group","n")
gp.samp.df <- merge(data.frame(group=gp.orig,pretty=gp.samp,order=seq(length(gp.orig))), gp.df )
gp.samp.df <- sort(gp.samp.df, f=~order)
res$pretty <- with( gp.samp.df, rep(pretty,n))

   group var pretty
6      3 0.5    3.0
7      3 0.2    3.0
12     5 0.4    5.0
13     5 0.6    5.0
61     3 0.5    3.1
71     3 0.2    3.1
62     3 0.5    3.2
72     3 0.2    3.2
3      2 0.3    2.0
4      2 0.4    2.0
5      2 0.8    2.0

应该很笼统。如果您想要超过 10 个组,则必须使用基于文本的方法来计算“漂亮”版本,因为它是基于数字的,因此这将覆盖。例如。第11组3将被计算为3+10*.1=4

【讨论】:

  • 您好,您建议使用一些基于文本的方法来计算“漂亮”版本。由于我正在处理一个庞大的数据集,所以这样做并不方便。您还有其他建议或想法来自动解决此问题吗?谢谢。
  • make.unique 似乎做得很好。请参阅@JoshOBrien 的回答。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-07-05
  • 1970-01-01
  • 1970-01-01
  • 2019-06-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多