【问题标题】:Conditionally sized sample from data.table来自 data.table 的有条件大小的样本
【发布时间】:2017-03-18 22:09:24
【问题描述】:

我一直在尝试寻找解决此问题的方法,并希望社区可以提供一些启发。

我有一个包含客户活动信息的大型 data.table,如下所示:

library(data.table)
library(dplyr)

DF = as.data.table(NULL)
cust_index = as.data.table(seq(1000,10000,3)) # list of unique customers
colnames(cust_index) = "cust_id"

# create a list of all customer activity - each cust_id represents an active event

for (cust in cust_index$cust_id){
  each_cust = as.data.table(rep(cust, sample(1:17,1, replace=FALSE)))
  DF = bind_rows(DF, each_cust)
  }
rm(each_cust)
colnames(DF) = "cust_id"
setkey(DF, cust_id)

# add dummy data for activity
DF[, A:= sample(x = c(0,1), size = nrow(DF), replace = TRUE)]
DF[, B:= sample(x = c(0,1), size = nrow(DF), replace = TRUE)]
DF[, C:= sample(x = c(0,1), size = nrow(DF), replace = TRUE)]

我想从 DF 中抽取最多 4 个客户观察结果。

到目前为止,我使用了一个函数来对单个客户的观察结果进行采样:

sample.cust = function(x){
  if (nrow(x)<4) {
    cust_sample = x 
  } else {
    cust_sample = x[sample(1:4,replace=FALSE)]
  }
  return(cust_sample)
}

.. 从 for 循环中调用。

for (cust in cust_index$cust_id){
  cust.sample = train.data[.(cust), sample.cust(.SD)]
  train.sample = bind_rows(train.sample, cust.sample)
 }

.. 但是上面的 for 循环永远不会终止。

到目前为止,我已经尝试了各种 := 并设置组合来实现这一目标,但没有成功。任何建议都将不胜感激,因为我认为这将是一个相当微不足道的解决方案。

非常感谢, M.

【问题讨论】:

  • dplyr 包添加

标签: r loops data.table


【解决方案1】:

一个解决方案作为评论发布在一个现已删除的答案中,该答案使用数据表中的 .I 运算符进行索引:

DF[DF[,sample((.I), min(.N, 4), replace=FALSE), by=cust_id]$V1]

虽然这很有用,但它忽略了要采样的行数长度为 1 的情况。在 data.table 中包含函数调用可以获得正确的结果:

resamp = function(.N, .I){
  if(.N==1) .I else sample((.I), min(.N, 4))
}

DF[ DF[, resamp(.N, .I), by="cust_id"]$V1]

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-09-16
  • 2014-04-16
  • 2010-10-02
相关资源
最近更新 更多