【问题标题】:Elegant way to invoke multiple functions using R使用 R 调用多个函数的优雅方式
【发布时间】:2019-09-06 05:40:48
【问题描述】:

我有一组预处理函数,我最终调用它们来创建最终数据帧。如您所见,每个阶段的输出都作为输入传递给下一个阶段。

wrap_func = function(DF){  # Wrapper function which has all the above functions put together. 
T1 = transform_ids(DF)                                                          
print("Id transformation success")   #print statements are used for debugging purposes
T2 = transform_dates(T1)
print("date transformation success")
T3 = measurement_ids(T2)
print("measurement_ids transformation success")
T4 = oper_val_concepts(T3)
print("operator transformation success")
T5 = range_values(T4)
print("range capture success")
T6 = col_format(T5)
print("column formatting success")
T7 = missing_impute(T6,def_val)
print("Missing value Imputation success")
T7 = T7[c(                                                     # reordering the column display
"measurement_id","person_id")]
 return(T7)
 } 

DF = wrap_func(dfm)

有什么优雅的写法吗?

这篇文章有类似的场景,但它是在 Python 中。related post

你能帮我用 R 把它变得优雅吗?

【问题讨论】:

  • 您熟悉来自magrittr 的管道(%>%)以及像dplyr 这样的包吗?如今,这种工作流程在 R 中非常普遍。
  • 感谢您的回复。我在我的个人函数中使用了%>% 运算符来对数据框执行操作。我是 R 新手,所以真的不知道如何在这种情况下使用它来调用它们。
  • %>% 基本上完全符合您的要求,请参阅r4ds.had.co.nz/pipes.html
  • 当然。谢谢会调查它

标签: r performance function dataframe


【解决方案1】:

一种解决方案是:

pipeline <- function(DF){
 DF %>%
 transform_ids() %T>%                                                          
  cat("Id transformation success\n") %>%
 transform_dates() %T>%
  cat("date transformation success\n") %>%
 measurement_ids() %T>%
  cat("measurement_ids transformation success\n") %>%
 oper_val_concepts() %T>%
  cat("operator transformation success\n") %>%
 range_values() %T>%
  cat("range capture success\n") %>%
 col_format() %T>%
  cat("column formatting success\n") %>%
 missing_impute(def_val) %T>%
  cat("Missing value Imputation success\n") %>%
 .[c("measurement_id","person_id")]
} 

DF <- pipeline(dfm)

地点:

  • magrittr%&gt;% 允许您将左侧的结果作为第一个参数传递给下一个函数。

  • magrittr%T&gt;% 允许您返回左侧值(因为您不想将打印的字符串通过管道传递到下一步)

  • 末尾的点 . 指的是管道对象(这里是数据框)

如果您更喜欢使用print() 而不是cat,请务必将其放在大括号{print("Hello World!"} 之间

如果您愿意放弃调试消息(或将其集成到每个独特的功能中)您可以使用purrrcompose

pipeline <- compose(~ .x[c("measurement_id","person_id")], ~ missing_impute(.x, def_val), col_format, range_values, oper_val_concepts, measurement_ids, transform_dates, transform_ids)

DF <- pipeline(dfm)

请注意,这里的函数是从右到左应用的(但您可以使用选项 compose(..., .dir = "forward") 从左到右应用)

【讨论】:

  • 谢谢。会尝试。赞成。但是这个仍然和旧的一样长。感谢你的帮助。会尝试
  • 您可能会使用更简洁的解决方案,但代价是放弃打印的字符串。例如,您可以使用 purrr 的 compose 创建一个独特的功能。
  • 没有打印语句我很好。
  • 我用compose 编辑了我的答案,这使它成为一个单行字!
  • 所以,从right to left 撰写作品。在上面的问题中,transform_ids 是第一个必须执行的函数?
猜你喜欢
  • 1970-01-01
  • 2019-05-09
  • 1970-01-01
  • 2014-11-20
  • 1970-01-01
  • 2014-09-17
  • 2021-05-27
  • 2013-01-25
  • 2013-11-14
相关资源
最近更新 更多