代码之家  ›  专栏  ›  技术社区  ›  Pierre Gramme

用dplyr写t而不是true

  •  1
  • Pierre Gramme  · 技术社区  · 6 年前

    由于懒惰,我经常使用缩写 T 对于 TRUE . 在这里我观察到一种奇怪的行为 dplyr ,但并不总是被接受。

    这个例子崩溃了( incompatible value for ``na.rm`` argument ):

    df = head(iris)
    mutate(df, n = n_distinct(Species, na.rm=T))
    

    但这些例子是有效的:

    mutate(df, n = n_distinct(Species, na.rm=TRUE))
    df$n = n_distinct(df$Species, na.rm=T)
    mutate(df, m = mean(Sepal.Length, na.rm=T))
    

    当然,这里的简单方法是避免缩写和键入 真的 . 但这也不管用:

    b = TRUE
    mutate(df, n = n_distinct(Species, na.rm=b))
    

    对这种行为有什么可以理解的解释吗?非标准评价不知何故?知道要避免什么会帮助我花更少的时间调试我的代码。

    2 回复  |  直到 6 年前
        1
  •  1
  •   akrun    6 年前

    建议使用全名而不是缩写 T F 因为当一个名为 T F . 但是,我们不能像 TRUE 作为名称

    TRUE <- 1:5
    

    true中的错误<-1:5:赋值的左侧无效(do_set)

    尽管字符串或反引号可以做到这一点

    `TRUE` <- 1:5 # but it is not recommended
    

    检查对象的一个选项是使用bang-bang运算符

    out1 <- mutate(df, n = n_distinct(Species, na.rm=!!T))
    out2 <- mutate(df, n = n_distinct(Species, na.rm=!!b))
    out3 <- mutate(df, n = n_distinct(Species, na.rm=TRUE))
    identical(out1, out3)
    #[1] TRUE
    identical(out1, out2)
    #[1] TRUE
    
        2
  •  1
  •   Pierre Gramme    5 年前

    这是由于一个错误,现在已修复。感谢Tidyverse团队!

    https://github.com/tidyverse/dplyr/issues/3686