Home > other >  R For loop/map2 that iterates over two lists
R For loop/map2 that iterates over two lists

Time:10-21

I've read [this][1] and [this][2], but am unable to adapt it to my use case. I am trying to use the openxlsx function writeData to write several dataframes I saved in a vector along with the names of the workbook sheets, also saved in a vector:

names_of_worksheets <- c(
  "total_suppliers",
  "nato_fvey_suppliers",
  "us_suppliers",
  "sole_sourcing",
  "single_sourcing",
  "geographic_risk_us_only",
  "foreign_dependence",
  "exposure_to_non_nato_fvey"
  )

names_of_dataframes <- c(
  total_suppliers,
  nato_fvey_suppliers,
  us_suppliers,
  sole_sourcing,
  single_sourcing,
  geographic_risk_us_only,
  foreign_dependence,
  exposure_to_non_nato_fvey
  )

The pseudo code I'd like to write is a for loop (which I think I can do in python) that iterates over two lists/vectors:

for (name_of_worksheet, name_of_dataframe in names_of_worksheets, names_of_data_frames) {
 writeData(workbook, name_of_worksheet, name_of_dataframe)
}

That of course doesn't work. I've tried map2 but gotten an error I can't deal with:

map2(names_of_worksheets, names_of_dataframes, writeData, workbook)

Error: Mapped vectors must have consistent lengths:
* `.x` has length 8
* `.y` has length 25

Any thoughts? Thanks! [1]: Looping over multiple lists with base R [2]: R Loop Iterating Over Two Lists

CodePudding user response:

I think you might want to use list() instead of c() to gather your data frames.

The later will take all the columns of the data frames and put them as independent elements in a list (which is why you get inconsistent length error) while the former keeps them as separate elements. The map2 should work then for simultaneous iteration.

It looks like writeData takes workbook as first element and currently your map2 call would use it as third element, so maybe you want to rewrite it as

map2(names_of_worksheets, names_of_dataframes, function(x,y) writeData(workbook, x, y))
  • Related