Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

add_column in tibble with variable column name

Tags:

r

dplyr

tibble

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?

like image 444
Joe Avatar asked Aug 17 '17 17:08

Joe


1 Answers

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

like image 122
MrFlick Avatar answered Sep 30 '22 10:09

MrFlick