2

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

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)
) 

任何帮助将不胜感激。

4

2 回答 2

3

这是一个相当简单的解决方案,用于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"
于 2012-06-14T16:20:58.780 回答
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

于 2012-06-14T15:22:46.093 回答