【问题标题】:How to create an R function which applies function to more than one column in a dataset?如何创建将函数应用于数据集中多个列的 R 函数?
【发布时间】:2021-02-08 19:53:06
【问题描述】:

这是一个示例数据集:

library(tidyverse)
library(lubridate)

db_country <- tibble(country = c("Argentina", "Australia", "Austria"),
                     region = c("Americas", "Asia", "Europe"),
                     start_date = as.numeric(18487, 18487, 18487),
                     end_date = as.numeric(18500, 18500, 18500))

# A tibble: 3 x 4
  country   region   start_date end_date
  <chr>     <chr>         <dbl>    <dbl>
1 Argentina Americas      18487    18500
2 Australia Asia          18487    18500
3 Austria   Europe        18487    18500

我正在尝试制作一个将列中的所有值转换为日期格式的函数。这是我目前所拥有的:

mydate <- function(dataset, column) {
  dataset %>% mutate({{column}} := as_date({{column}}))

我希望能够为我所做的“列”参数输入多个列名。我不想为start_dateend_date 使用我的mydate() 函数两次,而是希望能够编写类似的内容并使用一行代码将该函数应用于多个列:(有点像@987654326 @函数)

mydate(db_country, start_date, end_date)

如何编辑我的函数来做到这一点?

非常感谢任何帮助:)

【问题讨论】:

    标签: r function date tidyverse lubridate


    【解决方案1】:

    你可以这样做:

    mydate <- function(dataset, ...) 
    {
      mutate(dataset, across(as.character(ensyms(...)), as_date))
    }
    

    允许以下管道友好的语法:

    db_country %>% mydate(start_date, end_date)
    
    #> # A tibble: 3 x 4
    #>   country   region   start_date end_date  
    #>   <chr>     <chr>    <date>     <date>    
    #> 1 Argentina Americas 2020-08-13 2020-08-26
    #> 2 Australia Asia     2020-08-13 2020-08-26
    #> 3 Austria   Europe   2020-08-13 2020-08-26
    
    

    【讨论】:

    • 我还看到在整个 rlang 框架内建议使用 as_name() 而不是 as.character()。我不能说我知道它的优点。我敢肯定至少有一个更安全的细微差别?它确实表明未来计划提供名称修复功能。
    • @Adam 是的,虽然我认为 应该 必须放在 sapply 中才能工作
    猜你喜欢
    • 1970-01-01
    • 2020-04-22
    • 2021-07-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多