How to create multiple columns in mutate() when the new names and values come from vectors?

In short, what I am trying to do is convert the code below into a single call to mutate():

for(i in seq(new_columns)) {
  new_column_name <- names(new_columns[i])
  new_column_sql_expression <- new_columns[i]
  result <- mutate(result,
    !!sym(new_column_name) := sql(new_column_sql_expression))

Context: result is a lazy table from the dbplyr interface. Every call to mutate() produces a new layer of select *, new_column_sql_expression as new_column_name from ... in result. I have 200+ columns to create, so instead of 200+ select statements each creating one new_column_name, I wish the generated SQL code would be a single select with all 200+ new columns in it.

This is similar to this (Passing named list to mutate (and probably other dplyr verbs)), but here the column names and values come from vectors, as opposed to directly from the code.

Thank you already for reading my question.

P.S.: I understand that 200+ columns in a SQL table is bad design. This is part of a "stress test" trying to anticipate the consequences of bad practices by uninformed end users.

Well, I've solved it myself:

commands <- unlist(pmap(list(names(new_columns), new_columns), ~rlang::exprs(!!..1 := sql(!!..2))))
result <- mutate(result, !!!commands)

Kind regards!

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.