带有可变列名的tibble中的add_column [英] add_column in tibble with variable column name

查看:122
本文介绍了带有可变列名的tibble中的add_column的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此代码不适用于在标题中添加列:

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)

我收到错误消息:

  Error: unexpected '=' in "add_column(df, mycols[[2]] ="

$ b中的意外'='
$ b

但是此代码有效:

But this code works:

  add_column(df, "Bananas" = 7)

为什么?

我不知道值的 mycols提前值。这就是为什么我将代码编写为变量的原因。在dplry中不可能吗?

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?

推荐答案

您可以使用

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

请注意 !! := := 允许您使用变量作为参数名称,而 !! 将表达式扩展为一个strin g。

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

这篇关于带有可变列名的tibble中的add_column的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆