(非常)业余编码员和统计员在R中处理问题。
我有四个整数列表:A,B,C,D。
A <- [1:133]
B <- [1:266]
C <- [1:266]
D <- [1:133, 267-400]
我希望R通过从每个列表中选择1项来生成所有排列(我知道这段代码将永远运行),然后取每个排列的平均值。因此,例如,[1,100,200,400] - &gt; 175.25。
理想情况下,我最终会得到所有这些手段的清单。
有什么想法吗?
答案 0 :(得分:1)
以下是我为一个较小但类似的问题执行此操作的方法:
A <- 1:13
B <- 1:26
C <- 1:26
D <- c(1:13, 27:40)
mymat <- expand.grid(A, B, C, D)
names(mymat) <- c("A", "B", "C", "D")
mymat <- as.matrix(mymat)
mymeans <- rowSums(mymat)/4
如果只是提升所有索引,你可能会崩溃R,但你可能会设置一个循环,就像这样(未经测试):
B <- 1:266
C <- 1:266
D <- c(1:133, 267:400)
for(A in 1:133) {
mymat <- expand.grid(A, B, C, D)
names(mymat) <- c("A", "B", "C", "D")
mymat <- as.matrix(mymat)
mymeans <- rowSums(mymat)/4
write.table(mymat, file = paste("matrix", A, "txt", sep = "."))
write.table(mymeans, file = paste("means", A, "txt", sep = "."))
rm(mymat, mymeans)
}
让他们全部。那仍然可能太大,在这种情况下你可以做一个嵌套循环,或循环D
(因为它是最大的)
或者,
n <- 1e7
A <- sample(133, size = n, replace= TRUE)
B <- sample(266, size = n, replace= TRUE)
C <- sample(266, size = n, replace= TRUE)
D <- sample(x = c(1:133, 267:400), size = n, replace= TRUE)
mymeans <- (A+B+C+D)/4
将为您提供大量的手段样本,并且不会花时间。
hist(mymeans)
答案 1 :(得分:1)
即使创建一个与你的排列一样大的平均值的向量也会耗尽你所有的记忆。您将不得不将其拆分为较小的问题,查找将对象写入excel,然后从内存中移除对象here(两者都在SO上)。
至于执行此操作的代码,我已尽量保持尽可能简单,以便它能够轻松“成长”。你的知识:
#this is how to create vectors of sequential integers integers in R
a <- c(1:33)
b <- c(1:33)
c <- c(1:33)
d <- c(1:33,267:300)
#this is how to create an empty vector
means <- rep(NA,length(a)*length(b)*length(c)*length(d))
#set up for a loop
i <- 1
#how you run a loop to perform this operation
for(j in 1:length(a)){
for(k in 1:length(b)){
for(l in 1:length(c)){
for(m in 1:length(d)){
y <- c(a[j],b[k],c[l],d[m])
means[i] <- mean(y)
i <- i+1
}
}
}
}
#and to graph your output
hist(means, col='brown')
#lets put a mean line through the histogram
abline(v=mean(means), col='white', lwd=2)