add_column in tibble with variable column name

对着背影说爱祢 提交于 2019-12-05 01:27:59

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!