我想在模型列表中应用函数。我想通过将模型的名称放在其输出之前来组织输出。以下是基于this r-help thread使用match.call()
的(非常)简化示例:
x <- rnorm(10)
y <- rnorm(10)
mod <- lm(y~x)
fun <- function(model){
name <- as.character(match.call()[[2]])
p <- summary(model)$coefficients[2,4]
return(paste(name, "; p =", p))
}
如果我将它喂给一个模型,它可以正常工作:
> fun(model=mod)
[1] "mod ; p = 0.901618595026321"
但是,如果我将它应用于名单或名称,它不起作用:
> lapply(list(mod, mod), fun)
[[1]]
[1] "[[ ; p = 0.901618595026321" "X ; p = 0.901618595026321"
[3] "i ; p = 0.901618595026321"
[[2]]
[1] "[[ ; p = 0.901618595026321" "X ; p = 0.901618595026321"
[3] "i ; p = 0.901618595026321"
> lapply(list(modA=mod, modB=mod), fun)
$modA
[1] "[[ ; p = 0.901618595026321" "X ; p = 0.901618595026321"
[3] "i ; p = 0.901618595026321"
$modB
[1] "[[ ; p = 0.901618595026321" "X ; p = 0.901618595026321"
[3] "i ; p = 0.901618595026321"
为清楚起见,我想要的是:
[[1]]
[1] "modA ; p = 0.901618595026321"
[[2]]
[1] "modB ; p = 0.901618595026321"
答案 0 :(得分:2)
您是否有理由不想在列表名称上使用lapply
?
fun2 = function(models, name){
model <- models[[name]]
p <- summary(model)$coefficients[2,4]
return(paste(name, "; p =", p))
}
mods = list(modA = mod, modB = mod)
lapply(names(mods), fun2, models = mods)
# [[1]]
# [1] "modA ; p = 0.828746440943558"
# [[2]]
# [1] "modB ; p = 0.828746440943558"
答案 1 :(得分:1)
试试这个,
mLst <- list(modA=mod, mobB=mod)
p <- lapply(mLst, function(m) summary(m)$coefficients[2,4])
as.list(mapply(function(n,p) paste(n,p, sep=" ; "), names(mLst), p))