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