Paul
Paul

Reputation: 33

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.

The following code creates 1 image and then stops. Why not the other 2 images?

“MatrixFunction” is my own function that requires a df, column numbers, title. 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()
}

Upvotes: 1

Views: 230

Answers (2)

MrGumble
MrGumble

Reputation: 5766

Avoid for-loops in R. 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,

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)

Upvotes: 2

tonytonov
tonytonov

Reputation: 25608

You are overwriting your file over and over again. There's an obvious typo: mypath <- paste("testing", i). In that case, you will create tree separate files instead of one.

Upvotes: 3

Related Questions