R 如何使用字符向量的元素作为使用非标准求值的函数的符号参数:=运算符
我正在尝试编写一个函数,它接受变量名的字符向量作为符号参数 以下是从R 如何使用字符向量的元素作为使用非标准求值的函数的符号参数:=运算符,r,tidyverse,rlang,R,Tidyverse,Rlang,我正在尝试编写一个函数,它接受变量名的字符向量作为符号参数 以下是从questionr数据包中的“生育率”数据集中获取的一些数据。重要的是,它包含一些带标签的数据列 library(tidyverse) library(labelled) df <- structure(list(id_woman = structure(c(391, 1643, 85, 881, 1981, 1072, 1978,
questionr
数据包中的“生育率”数据集中获取的一些数据。重要的是,它包含一些带标签的数据列
library(tidyverse)
library(labelled)
df <- structure(list(id_woman = structure(c(391, 1643, 85, 881, 1981,
1072, 1978, 1607, 738), label = "Woman Id",
format.spss = "F8.0"),
weight = structure(c(1.80315, 1.80315, 1.80315, 1.80315,
1.80315, 0.997934, 0.997934, 0.997934, 0.192455),
label = "Sample weight", format.spss = "F8.2"),
residency = structure(c(2, 2, 2, 2, 2, 2, 2, 2, 2),
label = "Urban / rural residency",
labels = c(urban = 1, rural = 2),
class = "haven_labelled"),
region = structure(c(4, 4, 4, 4, 4, 3, 3, 3, 3), label = "Region",
labels = c(North = 1, East = 2, South = 3, West = 4),
class = "haven_labelled")),
row.names = c(NA, -9L), class = c("tbl_df", "tbl", "data.frame"))
他们退回了这个:
id_woman weight residency region
<dbl> <dbl> <fct> <dbl+lbl>
1 391 1.80 rural 4 [West]
2 1643 1.80 rural 4 [West]
3 85 1.80 rural 4 [West]
4 881 1.80 rural 4 [West]
5 1981 1.80 rural 4 [West]
6 1072 0.998 rural 3 [South]
7 1978 0.998 rural 3 [South]
8 1607 0.998 rural 3 [South]
9 738 0.192 rural 3 [South]
在这种情况下,我们必须评估(
!!
)
my.func(!!var.names[1])
#一个tibble:9x4
#id_女子体重居住区
#
#1391 1.80住宅4[西]
#2 1643 1.80住宅4[西部]
#3851.80住宅4[西]
#4881 1.80住宅4[西]
#5 1981 1.80居住4[西部]
#61072 0.998住宅3[南]
#7 1978 0.998居住3[南]
#8 1607 0.998居住3[南]
#9738 0.192居住3[南]
my.func(residency)
my.func("residency")
id_woman weight residency region
<dbl> <dbl> <fct> <dbl+lbl>
1 391 1.80 rural 4 [West]
2 1643 1.80 rural 4 [West]
3 85 1.80 rural 4 [West]
4 881 1.80 rural 4 [West]
5 1981 1.80 rural 4 [West]
6 1072 0.998 rural 3 [South]
7 1978 0.998 rural 3 [South]
8 1607 0.998 rural 3 [South]
9 738 0.192 rural 3 [South]
var.names <- c("residency", "region")
my.func(var.names[1])
Error: The LHS of `:=` must be a string or a symbol
Call `rlang::last_error()` to see a backtrace
my.func(rlang::sym(var.names[1]))
Error: The LHS of `:=` must be a string or a symbol
Call `rlang::last_error()` to see a backtrace
my.func(!!var.names[1])
# A tibble: 9 x 4
# id_woman weight residency region
# <dbl> <dbl> <fct> <dbl+lbl>
#1 391 1.80 residency 4 [West]
#2 1643 1.80 residency 4 [West]
#3 85 1.80 residency 4 [West]
#4 881 1.80 residency 4 [West]
#5 1981 1.80 residency 4 [West]
#6 1072 0.998 residency 3 [South]
#7 1978 0.998 residency 3 [South]
#8 1607 0.998 residency 3 [South]
#9 738 0.192 residency 3 [South]