【问题标题】:sym not working with vector has more than 1 elementsym 不适用于向量有超过 1 个元素
【发布时间】:2021-12-23 16:59:26
【问题描述】:
df <- data.frame(A = c(1,1,1), B = c(2,2,3))
variables <- c("A", "B") 
dplyr::count(df, !!!rlang::sym(variables))
Error: Only strings can be converted to symbols
Run `rlang::last_error()` to see where the error occurred.

如果variablesAB,但不能同时是两者,它都有效。

【问题讨论】:

    标签: r tidyverse rlang sym


    【解决方案1】:

    为此需要syms。根据?sym

    sym() 从字符串创建符号,syms() 从字符向量创建符号列表。

    dplyr::count(df, !!!rlang::syms(variables))
      A B n
    1 1 2 2
    2 1 3 1
    

    【讨论】:

    • 啊,我没看到有s
    【解决方案2】:

    有几种方法可以做到这一点。 OPs 方法的问题是sym() 将返回一个符号,但我们需要一个符号列表。使用 akrun 的优秀答案,使用矢量化 symspurrr::map(sym)

    或者,没有 rlang、双/三重刘海等,我们可以在 dplyr 中使用 across(all_of()) 进行操作

    Library(tidyverse)
    
    count(df, !!!syms(variables)) #As suggested by @akrun
    
    count(df, across(all_of(variables)))
    
    count(df, !!!map(variables, sym))
    
      A B n
    1 1 2 2
    2 1 3 1
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-10-15
      • 1970-01-01
      • 2023-03-12
      • 1970-01-01
      • 1970-01-01
      • 2011-01-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多