add_column in tibble with variable column name

Joe picture Joe · Aug 17, 2017 · Viewed 10.6k times · Source

This code doesn't work to add a column in tibble:

  library(tidyverse)
  df <- data.frame("Oranges" = 5)
  mycols <- c("Apples", "Bananas", "Oranges")
  add_column(df, mycols[[2]] = 7)

I get the error message:

  Error: unexpected '=' in "add_column(df, mycols[[2]] ="

But this code works:

  add_column(df, "Bananas" = 7)

Why?

I don't know the values of 'mycols' ahead of time. That's why I wrote my code for it to be a variable. Is this not possible in dplry?

Answer

MrFlick picture MrFlick · Aug 17, 2017

You can use one of the two options:

add_column(df, "{mycols[2]}" := 7)
add_column(df, !!(mycols[2]) := 7)

The first one is the more preferred style now where you can use glue strings to create parameter names. Otherwise you can use !! to inject the parameter name. Both require := allows you to use variables for parameter names (which you cannot do with the = that's normally used when calling a function).