mervebduman
mervebduman

Reputation: 1

Iterate through list of DFs, grab their listname and apply a function?

I have a list of data frames which are named correctly in the list. I want to create circos plots using those data frames and save them using a for loop.

Here is the script where I create the plot:

jpeg("df-name.jpeg")
circos.initialize(df$sectors, x = df$x)
circos.track(df$sectors, y = df$y,
             panel.fun = function(x, y) {
               circos.text(CELL_META$xcenter, 
                           CELL_META$cell.ylim[2] + mm_y(5), 
                           CELL_META$sector.index)
               circos.axis(labels.cex = 0.6)
             })
dev.off()

I think I need to do something like this but it doesn't work because it can't grab list names:

for (df in dflist) {
  jpeg(paste0(df, ".jpeg"))
  circos.initialize(df$sectors, x = df$x)
  circos.track(df$sectors, y = df$y,
             panel.fun = function(x, y) {
               circos.text(CELL_META$xcenter, 
                           CELL_META$cell.ylim[2] + mm_y(5), 
                           CELL_META$sector.index)
               circos.axis(labels.cex = 0.6)
             })
  dev.off()
}

Although this grabs list names, it can't grab data frames:

dfnames <- names(dflist)

for (df in seq_along(dflist)) {
  print(df.names[i])
}

How can I both grab list names and data frames and use them in a for loop in R? I appreciate very much the answers.

I found the answer, it was that simple:

for (name in names(dflist)) {
  df <- dflist[[name]]
  drawCircos(df, name)
}

I wrap the script in a function and applied the for loop above.

Upvotes: 0

Views: 43

Answers (1)

akrun
akrun

Reputation: 887521

We may loop over the names of the dflist, subset the data inside to create a temporary object df and use the same code

for (nm in names(dflist)) {
  jpeg(paste0(nm, ".jpeg"))
  df <- dflist[[nm]]
  circos.initialize(df$sectors, x = df$x)
  circos.track(df$sectors, y = df$y,
             panel.fun = function(x, y) {
               circos.text(CELL_META$xcenter, 
                           CELL_META$cell.ylim[2] + mm_y(5), 
                           CELL_META$sector.index)
               circos.axis(labels.cex = 0.6)
             })
  dev.off()
}

Upvotes: 2

Related Questions