2016-02-05 32 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