【发布时间】:2011-04-12 13:20:34
【问题描述】:
我正在编写一些代码来为市场研究生成平衡的实验设计,特别是用于联合分析和最大差异缩放。
第一步是生成部分平衡未完成块 (PBIB) 设计。这是直接使用 R 包AlgDesign。
对于大多数类型的研究,这样的设计就足够了。然而,在市场研究中,人们希望控制每个区块中的订单效应。这是我希望得到帮助的地方。
创建测试数据
# The following code is not essential in understanding the problem,
# but I provide it in case you are curious about the origin of the data itself.
#library(AlgDesign)
#set.seed(12345)
#choices <- 4
#nAttributes <- 7
#blocksize <- 7
#bsize <- rep(choices, blocksize)
#PBIB <- optBlock(~., withinData=factor(1:nAttributes), blocksizes=bsize)
#df <- data.frame(t(array(PBIB$rows, dim=c(choices, blocksize))))
#colnames(df) <- paste("Item", 1:choices, sep="")
#rownames(df) <- paste("Set", 1:nAttributes, sep="")
df <- structure(list(
Item1 = c(1, 2, 1, 3, 1, 1, 2),
Item2 = c(4, 4, 2, 5, 3, 2, 3),
Item3 = c(5, 6, 5, 6, 4, 3, 4),
Item4 = c(7, 7, 6, 7, 6, 7, 5)),
.Names = c("Item1", "Item2", "Item3", "Item4"),
row.names = c("Set1", "Set2", "Set3", "Set4", "Set5", "Set6", "Set7"),
class = "data.frame")
** 定义两个辅助函数
balanceMatrix计算矩阵的余额:
balanceMatrix <- function(x){
t(sapply(unique(unlist(x)), function(i)colSums(x==i)))
}
balanceScore 计算“适合”的度量 - 分数越低越好,完美为零:
balanceScore <- function(x){
sum((1-x)^2)
}
定义一个随机重新采样行的函数
findBalance <- function(x, nrepeat=100){
df <- x
minw <- Inf
for (n in 1:nrepeat){
for (i in 1:nrow(x)){df[i,] <- sample(df[i, ])}
w <- balanceMatrix(df)
sumw <- balanceScore(w)
if(sumw < minw){
dfbest <- df
minw <- sumw
}
}
dfbest
}
主要代码
dataframedf是7组的平衡设计。每组将向受访者展示 4 个项目。 df 中的数值指的是 7 个不同的属性。例如,在 Set1 中,将要求受访者从属性 1、3、4 和 7 中选择他/她的首选选项。
每个集合中项目的顺序在概念上并不重要。因此,(1,4,5,7) 的排序与 (7,5,4,1) 相同。
但是,为了获得完全平衡的设计,每个属性将在每列中出现相同的次数。这种设计是不平衡的,因为属性 1 在第 1 列中出现了 4 次:
df
Item1 Item2 Item3 Item4
Set1 1 4 5 7
Set2 2 4 6 7
Set3 1 2 5 6
Set4 3 5 6 7
Set5 1 3 4 6
Set6 1 2 3 7
Set7 2 3 4 5
为了尝试找到更平衡的设计,我编写了函数findBalance。这通过在df 的行中随机抽样来随机搜索更好的解决方案。重复 100 次后,它会找到以下 最佳 解决方案:
set.seed(12345)
dfbest <- findBalance(df, nrepeat=100)
dfbest
Item1 Item2 Item3 Item4
Set1 7 5 1 4
Set2 6 7 4 2
Set3 2 1 5 6
Set4 5 6 7 3
Set5 3 1 6 4
Set6 7 2 3 1
Set7 4 3 2 5
这看起来更平衡,并且计算出的平衡矩阵包含很多。平衡矩阵计算每个属性在每列中出现的次数。例如,下表表明(在左上角的单元格中)属性 1 在第 1 列中根本没有出现两次,在第 2 列中出现两次:
balanceMatrix(dfbest)
Item1 Item2 Item3 Item4
[1,] 0 2 1 1
[2,] 1 1 1 1
[3,] 1 1 1 1
[4,] 1 0 1 2
[5,] 1 1 1 1
[6,] 1 1 1 1
[7,] 2 1 1 0
此解决方案的平衡分为 6,表示至少有 6 个不等于 1 的单元格:
balanceScore(balanceMatrix(dfbest))
[1] 6
我的问题
感谢您关注这个详细的示例。我的问题是如何将这个搜索功能重写为更系统?我想告诉 R:
- 最小化
balanceScore(df) - 通过更改
df的行顺序 - 受制于:已经完全受限
【问题讨论】:
标签: r mathematical-optimization