具有替换的数据子集

时间:2012-06-14 15:07:33

标签: r

我试图从替换数据中抽取一个子集,这里我给出一个简单的例子如下:

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

我只想根据组号对子集进行采样。如果选择组(例如,组= 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)
) 

非常感谢任何帮助。

2 个答案:

答案 0 :(得分: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"

答案 1 :(得分: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