在dplyr中操作动态创建的变量名 [英] Manipulating dynamically created variable names in `dplyr`

查看:66
本文介绍了在dplyr中操作动态创建的变量名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 lapply 表达式内创建了一组小标题,这些表达式稍后将被合并。我需要动态创建变量名。遵循此问题this ,我创建了这个最小的示例:

I am creating a set of tibbles inside a lapply expression that will later be merged. I need to dynamically create variable names. Following the suggestions in this question and this , I create this minimal example:

library(tidyverse)

name_v1 <- "first_variable"
name_v2 <- "second_variable"
name_v3 <- "third_variable"

tibble(
  !!name_v1 := c(1, 2),
  !!name_v2 := c(3, 4)
)

显然可以提供所需的输出。但是,我需要使用这两个来创建第三个变量。由于我不知道这些变量的名称,因此需要引用动态创建的变量。我试过了:

Which obviously gives the desired output. However, I need to create a third variable using these two. Since I do not "know" the name of these variables, I need to reference the ones that were dynamically created. I tried:

tibble(
  !!name_v1 := c(1, 2),
  !!name_v2 := c(3, 4),
  !!name_v3 := !!name_v1 / !!name_v2
)



tibble(
  !!name_v1 := c(1, 2),
  !!name_v2 := c(3, 4)
) %>%
  mutate(
    !!name_v3 := !!name_v1 / !!name_v2
  )

tibble(
  !!name_v1 := c(1, 2),
  !!name_v2 := c(3, 4),
  !!name_v3 := name_v1 / name_v2
)

但是所有三个都给出错误消息。如何访问和操作这些新创建的变量?

But all three give error messages. How can I access and manipulate these newly created variables?

推荐答案

您需要 sym

tibble(
  !!name_v1 := c(1, 2),
  !!name_v2 := c(3, 4),
  !!name_v3 := !!sym(name_v1) / !!sym(name_v2))
)

# A tibble: 2 x 3
#   first_variable second_variable third_variable
#            <dbl>           <dbl>          <dbl>
# 1              1               3          0.333
# 2              2               4          0.5  

这篇关于在dplyr中操作动态创建的变量名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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