假设我有一些像这样的列表
somelist <- list(a = 1, b = 2, c = 4, d = 8)
和一些像这样的功能
somefunction <- function (key, value) paste(replicate(value, key), collapse = "")
我想将somefunction
应用于所有somelist
的名称/值对。
一种方法:
sapply(names(somelist), function (name) somefunction(name, somelist[[name]]),
USE.NAMES = FALSE)
## [1] "a" "bb" "cccc" "dddddddd"
我可以像这样封装这个功能:
myapply <- function (somelist, somefunction, ...) {
sapply(names(somelist),
function (name) somefunction(name, somelist[[name]]),
...)
}
所以,
myapply(somelist, somefunction, USE.NAMES = FALSE)
## [1] "a" "bb" "cccc" "dddddddd"
我的问题:myapply
中是否存在类似R
(上图)的内容?