【发布时间】: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