当每次迭代的输出是data.frame时循环

时间:2012-03-14 06:02:58

标签: r apply

我想为以下数据进行循环。单次迭代的输出是data.frame。我的代码是:

Data <- structure(list(v = c(15L, 15L, 15L, 15L, 16L, 16L, 16L, 17L,
17L, 18L, 19L, 19L, 19L, 20L, 20L, 21L, 21L, 22L, 22L, 25L, 25L
), b = c(35L, 70L, 42L, 35L, 20L, 48L, 16L, 68L, 68L, 51L, 57L,
57L, 57L, 95L, 76L, 70L, 21L, 77L, 77L, 100L, 30L), r = c(7L,
14L, 14L, 14L, 5L, 15L, 6L, 16L, 20L, 17L, 9L, 12L, 18L, 19L,
19L, 10L, 5L, 14L, 21L, 12L, 6L), k = c(3L, 3L, 5L, 6L, 4L, 5L,
6L, 4L, 5L, 6L, 3L, 4L, 6L, 4L, 5L, 3L, 5L, 4L, 6L, 3L, 5L),
    lambda = c(1L, 2L, 4L, 5L, 1L, 4L, 2L, 3L, 5L, 5L, 1L, 2L,
    5L, 3L, 4L, 1L, 1L, 2L, 5L, 1L, 1L)), .Names = c("v", "b",
"r", "k", "lambda"), class = "data.frame", row.names = c(NA,
-21L))

library(AlgDesign)
BIB <- list()
for(i in 1:nrow(Data)){
BIB[[i]] <- data.frame(optBlock(~., withinData = factor(1:Data[i, "v"]), blocksize = rep(Data[i, "k"], Data[i, "b"]))$Blocks)
dimnames(BIB[[i]]) <- list(1:Data[i, "k"], paste("Block", 1:Data[i, "b"], sep = " "))
}
BIB

我想知道是否有简单的方法来完成同样的任务。任何帮助将受到高度赞赏。感谢

1 个答案:

答案 0 :(得分:0)

BIB <- list()
for(i in 1:nrow(Data)){
BIB[[i]] <- data.frame(optBlock(~., withinData = factor(1:Data[i, "v"]), blocksize = rep(Data[i, "k"], Data[i, "b"]))$Blocks)
dimnames(BIB[[i]]) <- list(1:Data[i, "k"], paste("Block", 1:Data[i, "b"], sep = "_"))
}

print(BIB)