我已经实现了几个函数,其中一些函数表现得非常相似,并且共享一些相同的结构。但是,我打算在我的包装器函数中更有效地重用代码,以便使函数体更小,以便于测试和调试。我试图找到更好的方法来构建尽可能小的包装函数。如何在包装函数中轻松有效地重复使用代码?多次有效使用相同代码结构的策略是什么?任何人都可以给我一些想法来克服这个问题吗?有什么想法吗?
obj.List
可以是data.frame列表,intList
可以是整数列表列表作为位置索引,val.List
可以是数字向量列表, threshold
可以是数字标量。 这是包装函数,其中两个小子函数的代码共享相同的模式:
myFunc <- function(obj.List, intList, threshold, ...) {
#
func.1 <- function() {
keepIdx <- lapply(intList, function(ele_) {
keepMe <- sapply(val.List, function(x) x<=threshold)
res <- ele_[keepMe]
})
expand.Keep <- Map(unlist,
mapply(extractList, obj.List, keepIdx))
return(expand.Keep)
}
func.2 <- function() {
dropIdx <- lapply(intList, function(ele_) {
drop_ <- sapply(val.List, function(x) x > threshold)
res <- ele_[drop_]
})
expand.drop <- Map(unlist,
mapply(extractList, obj.List, keepIdx))
return(expand.drop)
}
# then use the output of func.1 and func.2 as an argument for another function
# in this wrapper
# how can I make this wrapper more efficient ? How to resue the code ?
}
我只是想让这个包装器的函数体变小,而我可以在包装器中调用func.1,func.2作为参数来触发另一个子函数。我怎样才能做到这一点?有效地优化上面包装函数的代码结构吗?
答案 0 :(得分:0)
正如我先前所说,使用更正式的。它使各个组件的工作方式更加清晰,并使您可以更轻松地拆分代码。
我还没有能够测试,看看这是否有效,但是没有提供,但这里有一个例子说明你如何开始将它分开。
# This function mirrors most of what func.1 and func.2 do
unlistAndSelect <- function(intList, val.list, threshold, selection.method) {
# Making use of declaring other variables in lapply
keepIdx <- lapply(intList, selectionFunction,
val.list = val.list, threshold = threshold,
selection.fun = selection.method)
# unlist
expand.Keep <- Map(unlist, mapply(extractList, obj.List, keepIdx))
# Return result
return(expand.Keep)
}
# Mirrors most of dropIdx and keepIdx passing a selection method
selctionFunction <- function(ele_, val.list, selection.fun) {
keepMe <- sapply(val.List, selection.fun)
res <- ele_[keepMe]
}
# Your two selection methods
selectGEQ <- function(x) x <= threshold
selectLT <- function(x) x > threshold
# unlistAndSelect(... , selection.method = selectGEQ) will have similar results to function 1
# unlistAndSelect(... , selection.method = selectLT) will have similar results to function 1
myFunc <- function(obj.List, intList, threshold, ...) {
# then use the output of func.1 and func.2 as an argument for another function
# in this wrapper
# how can I make this wrapper more efficient ? How to resue the code ?
}
我还应该注意,我认为你可以重写选择方法,但是我没有在这个例子中,因为你需要小心处理它们的数据结构。