嵌套 for 循环以创建根据列表命名的直方图
nested for loop to create histograms named according to list
我是 R 的新手,需要创建一堆直方图,这些直方图根据他们来自的人群命名。当我尝试 运行 没有 "names" 部分的循环时,它工作正常。下面的代码循环遍历名称列表并按顺序应用它们,但我最终得到了 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))
}
}
尝试制作一个独特的迭代器,并使用它,而不是迭代 table 列表本身。只是更容易看到发生了什么。例如:
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()
在这种情况下,您的问题是 name 和 table 实际上是链接的,但是您有两个 for 循环,因此实际上生成了 table 和 name 的每个组合。
我是 R 的新手,需要创建一堆直方图,这些直方图根据他们来自的人群命名。当我尝试 运行 没有 "names" 部分的循环时,它工作正常。下面的代码循环遍历名称列表并按顺序应用它们,但我最终得到了 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))
}
}
尝试制作一个独特的迭代器,并使用它,而不是迭代 table 列表本身。只是更容易看到发生了什么。例如:
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()
在这种情况下,您的问题是 name 和 table 实际上是链接的,但是您有两个 for 循环,因此实际上生成了 table 和 name 的每个组合。