add_column in tibble with variable column name

11,725

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

Share:
11,725
Joe
Author by

Joe

Useful links for Mathematics Stack Exchange: https://math.meta.stackexchange.com/questions/9959/how-to-ask-a-good-question In particular, to increase your chances of having your question answered instead of closed: explain the context of your problem (where is it from), state your problem clearly, show your attempt at solving your problem, and explain where you are stuck or confused. DO NOT simply write a question with "PLZ HELP!" https://math.meta.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference To get started, try: putting $ on either side of math, as in $1+2$ using ^ for superscripts and _ for subscripts, with { } to group multiple characters, as in $3^{1+2}$ for $3^{1+2}$ using \frac{ }{ } for fractions, as in $\frac{4}{5}$ for $\frac{4}{5}$ using \alpha, \beta, ... for greek letters $$\frac{ x_{n+1} + \alpha }{ x_n + \beta } = \gamma^3$$ would render like this: $$\frac{ x_{n+1} + \alpha }{ x_n + \beta } = \gamma^3$$ $\LaTeX$

Updated on June 14, 2022

Comments

  • Joe
    Joe about 2 years

    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
    Joe almost 7 years
    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?
  • MrFlick
    MrFlick almost 7 years
  • David Tonhofer
    David Tonhofer over 4 years
    @Joe "You are in an environment of spiky little programming problems, all different"
  • Hendy
    Hendy about 3 years
    @MrFlick is there documentation on !!? I see := at that link, but not !! and both of these are new tricks to me! Thanks.
  • MrFlick
    MrFlick about 3 years
    @Hendy You might want to check out: tidyverse.org/blog/2019/06/rlang-0-4-0 or tidyeval.tidyverse.org/sec-why-how.html for more info on !!. You can also bring up the help page with ?"!!"