我们知道lapply
可用于在列表上迭代地调用函数。我们可以扭转这种局面吗?我的意思是,有一种简单的方法可以在一个函数列表上迭代一个数据帧吗?
我有一些函数都采用相同的参数,即一个数据框。虽然我可以将它们全部放在一个函数中,但我希望将它们分开,以便我可以在需要时快速调用它们。这是功能列表,
> (funsList <- list(.BA, .TB, .OBP, .SLG, .IsoPow, .RC))
[[1]]
function (x)
with(x, h/ab)
[[2]]
function (x)
with(x, (h - x2b - x3b - hr) + 2 * x2b + 3 * x3b + 4 * hr)
[[3]]
function (x)
with(x, round((h + bb + hbp)/(ab + sf + bb + hbp), 3))
[[4]]
function (x)
with(x, round(((h - x2b - x3b - hr) + 2 * x2b + 3 * x3b + hr)/ab,
3))
[[5]]
function (x)
with(x, round((x2b + 2 * x3b + 3 * hr)/ab, 3))
[[6]]
function (x)
{
with(x, round(((h + bb - cs + hbp - gidp) * (tb + (0.26 *
(bb - ibb + hbp)) + (0.52 * (sh + sf + sb))))/(ab + bb +
hbp + sh + sf), 1))
}
我摆弄了*apply
团伙。这不起作用:
sapply(seq(funsList), function(i){
eval(call('funsList'[[i]], 'dat'))
})
我觉得mapply
可以做到这一点,但我有时会绕mapply
和vapply
缠绕我的头。这是一个数据样本。列名称必须以tolower(colnames(pujols))
pujols <-
structure(list(yearID = 2001:2005, G = c(161L, 157L, 157L, 154L,
161L), G_batting = c(161L, 157L, 157L, 154L, 161L), AB = c(590L,
590L, 591L, 592L, 591L), R = c(112L, 118L, 137L, 133L, 129L),
H = c(194L, 185L, 212L, 196L, 195L), X2B = c(47L, 40L, 51L,
51L, 38L), X3B = c(4L, 2L, 1L, 2L, 2L), HR = c(37L, 34L,
43L, 46L, 41L), RBI = c(130L, 127L, 124L, 123L, 117L), SB = c(1L,
2L, 5L, 5L, 16L), CS = c(3L, 4L, 1L, 5L, 2L), BB = c(69L,
72L, 79L, 84L, 97L), SO = c(93L, 69L, 65L, 52L, 65L), IBB = c(6L,
13L, 12L, 12L, 27L), HBP = c(9L, 9L, 10L, 7L, 9L), SH = c(1L,
0L, 0L, 0L, 0L), SF = c(7L, 4L, 5L, 9L, 3L), GIDP = c(21L,
20L, 13L, 21L, 19L), G_old = c(161L, 157L, 157L, 154L, 161L
)), .Names = c("yearID", "G", "G_batting", "AB", "R", "H",
"X2B", "X3B", "HR", "RBI", "SB", "CS", "BB", "SO", "IBB", "HBP",
"SH", "SF", "GIDP", "G_old"), row.names = 70391:70395, class = "data.frame")
答案 0 :(得分:4)
这看起来很简单:
lapply(funsList, function(x) x(dat))