【问题标题】:Renaming column in tidyeval in dplyr 1.0在 dplyr 1.0 中重命名 tidyeval 中的列
【发布时间】:2021-03-28 01:51:42
【问题描述】:

我希望根据整洁评估中的接收变量生成新列。例如,

library(dplyr)

some_custom_measure <- function(.data, cola, colb) {
    .data %>% mutate("{{ cola }}_x_{{ colb }}" := {{ cola }} * {{ colb }})
}
iris %>% 
    some_custom_measure(Sepal.Length, Sepal.Width) %>% 
    head()

新列将命名为Sepal.Length_x_Sepal.Width

在自定义函数中形成新名称时,如何将变量作为字符串操作?我希望完成类似sepal_length_x_sepal_width

【问题讨论】:

    标签: r dplyr tidyverse rlang tidyeval


    【解决方案1】:

    您可以使用deparse(substitute(...)) 将每个变量名称捕获为字符串并将其存储到变量中。

    然后您可以处理该变量,但您喜欢操纵字符串。当您开始使用它时,请将变量放在列名规范中的单个大括号内。

    library(dplyr)
    
    some_custom_measure <- function(.data, cola, colb) {
    
        cola_name <- tolower(gsub("\\.", "_", deparse(substitute(cola))))
        colb_name <- tolower(gsub("\\.", "_", deparse(substitute(colb))))
    
        .data %>% mutate("{cola_name}_x_{colb_name}" := {{ cola }} * {{ colb }})
    }
    
    iris %>% 
        some_custom_measure(Sepal.Length, Sepal.Width) %>% 
        head()
    #>   Sepal.Length Sepal.Width Petal.Length Petal.Width Species
    #> 1          5.1         3.5          1.4         0.2  setosa
    #> 2          4.9         3.0          1.4         0.2  setosa
    #> 3          4.7         3.2          1.3         0.2  setosa
    #> 4          4.6         3.1          1.5         0.2  setosa
    #> 5          5.0         3.6          1.4         0.2  setosa
    #> 6          5.4         3.9          1.7         0.4  setosa
    #>   sepal_length_x_sepal_width
    #> 1                      17.85
    #> 2                      14.70
    #> 3                      15.04
    #> 4                      14.26
    #> 5                      18.00
    #> 6                      21.06
    

    【讨论】:

    • 谢谢!另外,我发现as_name(enquo(...)) 中有rlang
    • 我推荐使用rlang::as_label(),与deparse()不同,它保证返回长度为1的字符串。 rlang::as_name() 变体还检查输入是否为单个名称,而 as_label() 可用于任何表达式。
    猜你喜欢
    • 2021-01-18
    • 2018-02-27
    • 1970-01-01
    • 2014-02-25
    • 1970-01-01
    • 2018-09-08
    • 2018-01-20
    • 1970-01-01
    • 2019-02-28
    相关资源
    最近更新 更多