首页 > 解决方案 > 如何对数据集和模型执行迭代的、受限的排列?

问题描述

我正在尝试为我的数据创建许多排列,但要保留我的分层设计。我需要对每个随机数据集进行建模,然后提取系数。

我尝试使用gtools包的permute(),但它没有按照我的需要分层。该permute包的shuffleSet()声称可以工作,但我找不到任何有关如何使用 apermutationMatrix进行建模的文档。我使用了一个 for 循环:

library(permute)
blks <- as.factor(df$block)
plts <- as.factor(df$plot)
CTRL <- how(within = Within(type = "free"), plots = Plots(strata = plts), blocks = blks) # set the way in which permute approaches the data


set.seed(1717)
no.perm <- 100 # set the number of permutations
random_model <- data.frame() # create a place to hold the result
for (i in 1:no.perm) {
  shuffled <- shuffle(nrow(df), control = CTRL) # permute the data according to CTRL design
  df_shuffled <- df[shuffled,] # since shuffle() returns integers, retrieve the data
  coefs <- summary(clogit(response ~ pred1 + pred2 + pred3 + strata(plot),data = df_shuffled))$coefficients # model and extract summary
  random_model <- rbind(random_model, coefs) # add to the results
}

如果我shuffle()独立运行这条线,我每次都会得到不同的结果。但是,整个循环返回相同的三个系数 100 次。我不确定我哪里出错了,但是有没有办法让我的循环对每个排列的数据集进行建模并返回一个摘要?

非常感谢!

标签: rfor-loopshufflepermute

解决方案


推荐阅读