Joe Joe - 2 months ago 11
R Question

add_column in tibble with variable column name

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 Source

Well, add_column seems to come from tibble rather than dplyr, but it does use the new tidy eval syntax. You can use

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

Note the !! and :=. The := allows you to use variables for parameter names and the !! expands the expression into a string.