嵌套for循环以创建根据列表命名的直方图

嵌套for循环以创建根据列表命名的直方图,r,for-loop,graph,histogram,nested-loops,R,For Loop,Graph,Histogram,Nested Loops,我是R新手,需要创建一组直方图,这些直方图是根据它们来自的人群命名的。当我尝试在没有“名称”部分的情况下运行循环时,它工作得很好。下面的代码在名称列表中循环并按顺序应用它们,但我最终得到了3364个相同的精确直方图版本。如果有人有任何建议,我将不胜感激 popFiles <- list.files(pattern = "*.txt") # generates a list of the files I'm working with popTables <- lapply(popFil

我是R新手,需要创建一组直方图,这些直方图是根据它们来自的人群命名的。当我尝试在没有“名称”部分的情况下运行循环时,它工作得很好。下面的代码在名称列表中循环并按顺序应用它们,但我最终得到了3364个相同的精确直方图版本。如果有人有任何建议,我将不胜感激

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))
   }
}

popFiles尝试创建一个不同的迭代器,并使用它,而不是遍历表列表本身。只是更容易看到发生了什么。例如:

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循环,因此实际上会生成表和名称的每个组合。

因为在循环中没有任何顺序发生,所以您会反复调用相同的柱状图。哇,对不起。完成!