13

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?

Joe
  • 662
  • 1
  • 7
  • 20

1 Answers1

30

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).

MrFlick
  • 195,160
  • 17
  • 277
  • 295
  • 1
    That worked, thank you. I see !! and := in the help file, but I don't understand the documentation, and I've never seen them used before. Are you able to briefly state what they do? – Joe Aug 17 '17 at 17:44
  • 3
    @Joe Take a look here: http://dplyr.tidyverse.org/articles/programming.html – MrFlick Aug 17 '17 at 17:58
  • @Joe "You are in an environment of spiky little programming problems, all different" – David Tonhofer Feb 26 '20 at 16:35
  • @MrFlick is there documentation on `!!`? I see `:=` at that link, but not `!!` and both of these are new tricks to me! Thanks. – Hendy Apr 09 '21 at 02:10
  • 1
    @Hendy You might want to check out: https://www.tidyverse.org/blog/2019/06/rlang-0-4-0/ or https://tidyeval.tidyverse.org/sec-why-how.html for more info on `!!`. You can also bring up the help page with `?"!!"` – MrFlick Apr 09 '21 at 03:20