我正在尝试使用sjlabelled::val_labels()
来应用值标签,其中变量名,要标记的值和标签都被准引号。
下面是一个不使用准引号的示例:
library(sjlabelled)
library(rlang)
library(magrittr)
mtcars.test <- mtcars %>%
val_labels(
gear = c("foo" = 1)
)
attributes(mtcars.test$gear)
#> $labels
#> foo
#> 1
对变量名使用四引号很容易,如果它是字符串,则值名似乎会自动取消引号:
variable <- "gear"
value <- 1
mtcars.test <- mtcars %>%
val_labels(
!!variable := c("foo" = value)
)
attributes(mtcars.test$gear)
#> $labels
#> foo
#> 1
卡住的地方是取消标注名称的引用:
label <- "foo"
mtcars.test <- mtcars %>%
val_labels(
!!variable := c(!!label := !!value)
)
#> `:=` can only be used within a quasiquoted argument
?val_labels
的文档讨论了准引用,但没有包含取消引用这三个元素中每个元素的示例。一种解决方法是分别构建命名向量并将其取消引用:
vector <- value
names(vector) <- label
mtcars.test <- mtcars %>%
val_labels(
!!variable := !!vector
)
attributes(mtcars.test$gear)
#> $labels
#> foo
#> 1
这完成了工作,但是我想知道是否有一种方法可以使用单线而不需要分配命名向量。