deparse(substitute())给出长度大于1的结果,具有长的特定变量名

时间:2017-01-11 16:38:25

标签: r

我有一个函数使用deparse(substitute())来保留作为参数传入的变量的名称。我错误地认为这个结果总是长度为1,但是我最近调试了一个错误,发现对于特定的输入,deparse(substitute())会返回更长的结果。不过,我不明白为什么。

这是一个可重复性最小的例子:

library(dplyr) # for %>%, which may be playing a role
dat <- data.frame(
  `The quick brown fox jumped over the lazy dog` = c("a", "b", "a", "b"),
  `The quick brown fox jumped` = 1:4,
  check.names = FALSE,
  stringsAsFactors = FALSE
)

my_function <- function(vec1){
  var_name <- deparse(substitute(vec1))
  var_name
}

首先返回长度为2的字符串:

my_function(dat$`The quick brown fox jumped over the lazy dog` %>% gsub("a", "A", .)) # length 2 
#> [1] "dat$`The quick brown fox jumped over the lazy dog` %>% gsub(\"a\", "
#> [2] "    \"A\", .)"

但是%>%管道在较短的字符串中是可以的,而且它不只是gsub

my_function(dat$`The quick brown fox jumped over the lazy dog` %>% tolower) # length 1
#> [1] "dat$`The quick brown fox jumped over the lazy dog` %>% tolower"
my_function(dat$`The quick brown fox jumped` %>% gsub("a", "A", .)) # length 1
#> [1] "dat$`The quick brown fox jumped` %>% gsub(\"a\", \"A\", .)"

因此,让我们尝试更长的变量名称:

dat$Thequickbrownfoxjumpedoverthelazydogthisisalongvariablename <- dat[[1]]
dat$Thequickbrownfoxjumpedoverthelazydogthisisalongvariablenameitgoesonandonandonandon <- dat[[1]]

其中任何一个都会导致长度为2的结果 - 只要还有一个%>%管道:

my_function(dat$Thequickbrownfoxjumpedoverthelazydogthisisalongvariablename %>% gsub("a", "A", .)) # length 2
#> [1] "dat$Thequickbrownfoxjumpedoverthelazydogthisisalongvariablename %>% "
#> [2] "    gsub(\"a\", \"A\", .)"
my_function(dat$Thequickbrownfoxjumpedoverthelazydogthisisalongvariablename %>% tolower) # length 2
#> [1] "dat$Thequickbrownfoxjumpedoverthelazydogthisisalongvariablename %>% "
#> [2] "    tolower"
my_function(dat$Thequickbrownfoxjumpedoverthelazydogthisisalongvariablenameitgoesonandonandonandon) # length 1
#> [1] "dat$Thequickbrownfoxjumpedoverthelazydogthisisalongvariablenameitgoesonandonandonandon"

长变量名称​​和 %>%管道的长度为2的结果是什么?或者还有其他事情发生了吗?

0 个答案:

没有答案