Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/84.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R:用额外的术语创建数据分区_R_R Caret - Fatal编程技术网

R:用额外的术语创建数据分区

R:用额外的术语创建数据分区,r,r-caret,R,R Caret,我有下面的data.frame(比下面的示例长) 我正在使用以下代码制作数据分区: library("caret") train = createDataPartition(df$group, p = 0.50) partition = df[train, ] 因此,它从每组中选取一个概率为0.5的受试者。 我在下面这个例子中的问题是,有时会从d组中选择一个主题,有时则不会(因为d组非常小)。我想创建一个约束,在我创建的每个分区中,将从每个组中选择一个主题 有什么好办法吗 我想出了一个不太优雅

我有下面的data.frame(比下面的示例长)

我正在使用以下代码制作数据分区:

library("caret")
train = createDataPartition(df$group, p = 0.50)
partition = df[train, ]
因此,它从每组中选取一个概率为0.5的受试者。 我在下面这个例子中的问题是,有时会从d组中选择一个主题,有时则不会(因为d组非常小)。我想创建一个约束,在我创建的每个分区中,将从每个组中选择一个主题

有什么好办法吗

我想出了一个不太优雅的解决方案,如下所示:

allGroupSamles <- c()
for (i in unique(df$groups))
{
  allGroupSamles <- c(allGroupSamles , sample(rownames(df[df$groups == i, ]) , 1, replace = TRUE))
}
allGroupSamles <- as.integer(allGroupSamles )

train = createDataPartition(df$groups, p = 0.50)[[1]]
train <- c(allGroupSamles , train)

partition= df[unique(train), ]

allGroupSamles您可以对
数据框使用
split
,并在每组中抽取一半记录或1个样本,以较大者为准:

# apply a function over the split data.frame
samples <- lapply(split(df, df$group), function(x) {

  # the function takes a random sample of half the records in each group
  # by using `ceiling`, it guarantees at least one record
  s <- sample(nrow(x), ceiling(nrow(x)/2))
  x[s,]
})

train <- do.call(rbind, samples)
#在split data.frame上应用函数

样本签出
库(dplyr)
。我认为
groupby()
sample\n()
符合你的目的。哇。。那太好了。。我的解决方案是可行的,但远没有这个好。。太棒了。如果我在100次迭代中迭代这些行,你认为我应该从tapply中提取函数吗?我不确定性能差异会是什么。我会用两种方法测试它,并使用
microbenchmark
库比较执行时间。我不认为
R
每次迭代都在重新定义函数,如果这是您所关心的
# apply a function over the split data.frame
samples <- lapply(split(df, df$group), function(x) {

  # the function takes a random sample of half the records in each group
  # by using `ceiling`, it guarantees at least one record
  s <- sample(nrow(x), ceiling(nrow(x)/2))
  x[s,]
})

train <- do.call(rbind, samples)
s <- tapply(1:nrow(df), df$group, function(x) {
  sample(x, ceiling(length(x)/2))
})

do.call(c, s)