【问题标题】:nested for loop to create histograms named according to list嵌套for循环以创建根据列表命名的直方图
【发布时间】:2016-02-05 21:03:31
【问题描述】:

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

【问题讨论】:

  • 因为你的循环中没有任何顺序发生,你一遍又一遍地调用同一个直方图。

标签: r for-loop graph histogram nested-loops


【解决方案1】:

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

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 的每个组合。

【讨论】:

  • 哎呀,对不起。完成!
猜你喜欢
  • 2021-12-19
  • 2017-08-24
  • 1970-01-01
  • 2016-02-14
  • 2018-06-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多