r - 如何有效地按组对数据进行子采样?

标签 r

我确实有一个类似的问题,在 this question 中有解释。 .与该问题类似,我有一个包含 3 列(id、组、值)的数据框。我想从每组中取出 n 个样本并进行替换,并生成一个较小的数据框,其中包含每组的 n 个样本。

但是,我在模拟代码中做了数百个子样本,基于 ddply 的解决方案在我的代码中使用起来非常慢。我试图重写一个简单的代码,看看我是否可以获得更好的性能,但它仍然很慢(如果不差的话,也不比 ddply 解决方案好)。下面是我的代码。我想知道是否可以提高性能

#Producing example DataFrame
dfsize <- 10
groupsize <- 7
test.frame.1 <- data.frame(id = 1:dfsize, group = rep(1:groupsize,each = ceiling(dfsize/groupsize))[1:dfsize], junkdata = sample(1:10000, size =dfsize))


#Main function for subsampling
sample.from.group<- function(df, dfgroup, size, replace){
  outputsize <- 1
  newdf <-df # assuming a sample cannot be larger than the original
  uniquegroups <- unique(dfgroup)
  for (uniquegroup in uniquegroups){
    dataforgroup <- which(dfgroup==uniquegroup)
    mysubsample <- df[sample(dataforgroup, size, replace),]
    sizeofsample <- nrow(mysubsample)
    newdf[outputsize:(outputsize+sizeofsample-1), ] <- mysubsample
    outputsize <- outputsize + sizeofsample
  }
  return(newdf[1:(outputsize-1),])
}

#Using the function
sample.from.group(test.frame.1, test.frame.1$group, 100, replace = TRUE)

最佳答案

这里有两个基于 plyr 的解决方案:

library(plyr)

dfsize <- 1e4
groupsize <- 7
testdf <- data.frame(
  id = seq_len(dfsize),
  group = rep(1:groupsize, length = dfsize),
  junkdata = sample(1:10000, size = dfsize))

sample_by_group_1 <- function(df, dfgroup, size, replace) {
  ddply(df, dfgroup, function(x) {
    x[sample(nrow(df), size = size, replace = replace), , drop = FALSE]
  })
}

sample_by_group_2 <- function(df, dfgroup, size, replace) {
  idx <- split_indices(df[[dfgroup]])
  subs <- lapply(idx, sample, size = size, replace = replace)

  df[unlist(subs, use.names = FALSE), , drop = FALSE]
}

library(microbenchmark)
microbenchmark(
  ddply = sample_by_group_1(testdf, "group", 100, replace = TRUE),
  plyr = sample_by_group_2(testdf, "group", 100, replace = TRUE)
)

# Unit: microseconds
#   expr  min   lq median   uq   max neval
#  ddply 4488 4723   5059 5360 36606   100
#   plyr  443  487    507  536 31343   100

第二种方法要快得多,因为它一步完成子集化 - 如果您能弄清楚如何一步完成,这通常是获得更好性能的任何简单方法。

关于r - 如何有效地按组对数据进行子采样?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16912186/

相关文章:

r - 使用 ggplot2 在 geom_col() 图表上方添加数据标签

r - 估计 lsmeans 的差异

r - 如何通过 id 将数据帧转换为 R 中的列表?

在 R 中使用 NA 重新编码变量

r - R 中 MACD 返回错误值

r - 将批量节点与属性合并时的重复

r - 当我渲染 R markdown 时隐藏包加载消息

mysql - RODBC sqlSave 的问题

r - 选择所有值都大于 x 的组

r - 如何每次检查向量 (R) 中是否有 n 个升序/降序值