简体   繁体   English

循环浏览R中的列表

[英]Looping through a list in R

I am trying to create 3 different .png images in R and save them to 3 different files - all at once. 我正在尝试在R中创建3个不同的.png图像并将它们保存到3个不同的文件中-全部一次。

The following code creates 1 image and then stops. 以下代码创建1张图片,然后停止。 Why not the other 2 images? 为什么没有其他2张图片?

“MatrixFunction” is my own function that requires a df, column numbers, title. “ MatrixFunction”是我自己的函数,需要df,列号,标题。 Each test type is also the name of a data frame. 每种测试类型也是数据框的名称。

Thank you. 谢谢。

testtype <- list("Grade4TopBottom", "Grade8TopBottom", "HSPATopBottom")

for(i in testtype){

    mypath <- paste("testing", testtype)
    png(mypath, width=1336, height=656)
    MatrixFunction(get(i), 8:19, "Title")
    dev.off()
}

You are overwriting your file over and over again. 您一次又一次地覆盖文件。 There's an obvious typo: mypath <- paste("testing", i) . 有一个明显的错别字: mypath <- paste("testing", i) In that case, you will create tree separate files instead of one. 在这种情况下,您将创建树状文件而不是一个文件。

Avoid for -loops in R . 避免在R for循环。 They are notorious slow. 他们臭名昭著的慢。

If you create your method as a function, it is easier to check for errors and you can apply lapply or sapply to it, 如果您将函数创建为函数, lapply容易检查错误,并且可以对其应用lapplysapply

testtype <- list("Grade4TopBottom", "Grade8TopBottom", "HSPATopBottom")
make.image <- function(n) {    
    obj <- mget(n, ifnotfound=NA)[[1]]
    if (is.na(obj)) return(FALSE)
    mypath <- paste("testing", n)
    png(mypath, width=1336, height=656)
    MatrixFunction(obj, 8:19, "Title")
    dev.off()
    return(TRUE)
}
# test:
make.image('Grade4TopBottom')  # should return TRUE
make.image('Nope')             # should return FALSE
sapply(testtype, make.image)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM