2016-02-05 33 views
0

我是R新手,需要创建一堆根据其来自的人群命名的直方图。当我尝试运行没有“名称”部分的循环时,它工作正常。下面的代码循环遍历名称列表并按顺序应用它们,但我最终得到了3,364个具有相同直方图的版本。如果有人有任何建议,我会很感激。嵌套循环创建根据列表命名的直方图

popFiles <- list.files(pattern = "*.txt") # generates a list of the files I'm working with 
popTables <- lapply(popFiles, read.table, header=TRUE, na.strings="NA") 
popNames <- read.table(file.path("Path to file containing names", "popNamesR.txt"), header=FALSE,) 
popNames <- as.matrix(popNames) 

name <- NULL 
table <- c(1:58) 

for (table in popTables){ 
    for (name in popNames){ 
     pVals <- table$p 
     hist(pVals, breaks=20, xlab="P-val", main=name)) 
    } 
} 
+0

因为循环内没有任何顺序发生,所以一次又一次地调用相同的直方图。 – mtoto

回答

0

尝试制作独特的迭代器,并使用它,而不是遍历表列表本身。这很容易看到发生了什么。例如:

pdf("Myhistograms.pdf")  
for(i in 1:length(popTables)){ 
    table = popTables[[i]] 
    name = popNames[i] 
    pVals = table$p 
    hist(pVals, breaks=20, xlab="P-val", main=name)) 
} 
dev.off() 

在这种情况下,你的问题是,名和表实际上是联系在一起,但你有两个for循环,所以实际上是生成的表和名称的每个组合。

+0

这工作完美。非常感谢! – Kayla

+0

想要将答案标记为正确的,那么? – CPhil

+0

抱歉,抱歉。完成! – Kayla