【问题标题】:Best practice using multiple null arguments in writing R function在编写 R 函数时使用多个空参数的最佳实践
【发布时间】:2019-07-02 13:09:13
【问题描述】:

我正在编写一个函数,该函数根据传递给它的变量对数据帧进行子集化。我在 Advanced R 中阅读以使用 is_null 函数检查空参数。我添加了 2 个参数,它们已经是 if/elseif/elseif/else。恐怕如果我添加更多参数,代码的可读性会受到很大影响。我的方法是最佳实践吗?

add_scores <- function(data,
                       study = NULL,
                       therapeutic_area = NULL ){

  if (is_null(study) & is_null(therapeutic_area)){

    temp <- data 

  } else if (!is_null(study) & is_null(therapeutic_area)){

    temp <- data %>% 
      filter(BC == study)

  } else if (is_null(study) & !is_null(therapeutic_area)) {

    temp <- data %>% 
      filter(PPDDIVISIONPRI == therapeutic_area)

  } else {

    temp <- data %>% 
      filter(
        BC == study & 
        PPDDIVISIONPRI == therapeutic_area)

  }

  return(

    temp %>% 
      mutate(ENROLLMENTRANK = dense_rank(desc(ENROLLMENTRATE)),
             CYCLETIMERANK = dense_rank(CYCLETIME)*2,
             TOTALRANK = dense_rank(ENROLLMENTRANK + CYCLETIMERANK)
             ) %>% 
      arrange(TOTALRANK, ENROLLMENTRANK, CYCLETIMERANK)
        )
}

【问题讨论】:

  • 你是对的,当你有太多这样的论点时,可用性会大大受到影响。尽可能限制它们,而是酌情将不同的功能卸载到不同的功能中。 — 哦,与此无关,return 在 R 中是不必要的,除非过早退出函数,并且在您的使用中它会对可读性产生负面影响。

标签: r


【解决方案1】:

已编辑:

在您的具体问题中,您可以分离出if 测试:

if(!is.null(study)) data <- filter(data, BC==study)

if(!is.null(therapeutic_area)) data <- filter(data, PPDDIVISIONPRI==therapeutic_area)

否则,正如您所指出的,排列的数量会迅速增加!

【讨论】:

  • @dhbrand 简单的错字,我修正了。
  • 如果我替换 ||与单|然后该函数有效,但仅当我传递所有参数时。如果我将 study 或treatment_area 保留为空,则会收到错误Error: Result must have length 6656, not 0。
猜你喜欢
  • 2016-09-18
  • 1970-01-01
  • 2014-12-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-08
  • 1970-01-01
相关资源
最近更新 更多