问题
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?
回答1:
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.
来源:https://stackoverflow.com/questions/45741498/add-column-in-tibble-with-variable-column-name