1

I have the following lists in R:

logFramesChartInfo <- list(columnName="quality_logframes_overall", guageChartTitle="Logframes", guageChartId="logframes_quality", histogramChartTitle="Logframes Quality")
indicatorsChartInfo <- list(columnName="quality_indicators_overall", guageChartTitle="Logframes", guageChartId="indicators_quality", histogramChartTitle="Indicators Quality")

I would like to call a function with each of them, and to reduce code redundancy I would like to use a loop to do this, e.g.

chartInfos <- list("logFramesChartInfo" = logFramesChartInfo, "indicatorsChartInfo" = indicatorsChartInfo)
for (key in ChartInfos) {
   myFunction(chartInfos[key])
}

To test this out, I use the following:

myFunction(chartInfos["logFramesChartInfo"])

This doesn't work - I am running this as part of an R Shiny application, and I don't get an error, rather the chart doesn't display.

If, however, I call my function using the logFramesChartInfo variable I defined above:

myFunction(logFramesChartInfo)

The chart displays.

So right now to display multiple charts, I have to make multiple calls as follows:

myFunction(logFramesChartInfo)
myFunction(indicatorsChartInfo)
...

How can I iterate over all of the chartInfos?

Shafique Jamal
  • 1,550
  • 3
  • 21
  • 45

1 Answers1

1

It looks like you just need to use [[ instead of [ to move down a level in the list. Your function is getting a list of length 1 and it doesn't know what to do with it. Compare:

length(chartInfos["logFramesChartInfo"])
# [1] 1

length(chartInfos[["logFramesChartInfo"]])
# [1] 4

You can read about the difference between the index operators here.