【发布时间】:2020-12-01 17:59:18
【问题描述】:
library(rpart)
# Fit 3 models
fit <- rpart(Kyphosis ~ Age + Number + Start, data = kyphosis)
fit2 <- rpart(Kyphosis ~ Age + Number + Start, data = kyphosis,
parms = list(prior = c(.65,.35), split = "information"))
fit3 <- rpart(Kyphosis ~ Age + Number + Start, data = kyphosis,
control = rpart.control(cp = 0.05))
# Combine into a single list
input <- list(fit, fit2, fit3)
# Define parameters for `myfun`
newdata <- kyphosis[1:20, -1]
rate <- 0.1
myfun <- function(mod, newdata, rate){
if(length(mod) == 1){
return(0)
}else apply(sapply(2:length(mod), function(x) rate * predict(mod[[x]], newdata = newdata)), 1, sum)
}
我希望我的最终输出 mylist 是一个长度为 3 的列表。列表中的第一个条目包含向量
myfun(mod = input[1], newdata = newdata, rate = rate)
第二个包含
myfun(mod = input[1:2], newdata = newdata, rate = rate)
第三个包含:
myfun(mod = input[1:3], newdata = newdata, rate = rate)
因此,最终输出 mylist 应该如下所示:
> mylist
[[1]]
[1] 0
[[2]]
[1] 0.027932897 0.091563089 0.027932897 0.081616742 0.091563089 0.091563089 0.091563089 0.091563089 0.091563089 0.027932897 0.091563089
[12] 0.091563089 0.081616742 0.081616742 0.091563089 0.091563089 0.091563089 0.091563089 0.091563089 0.081616742 0.072067103 0.008436911
[23] 0.072067103 0.018383258 0.008436911 0.008436911 0.008436911 0.008436911 0.008436911 0.072067103 0.008436911 0.008436911 0.018383258
[34] 0.018383258 0.008436911 0.008436911 0.008436911 0.008436911 0.008436911 0.018383258
[[3]]
[1] 0.07003816 0.18188567 0.07003816 0.12372201 0.18188567 0.18188567 0.18188567 0.18188567 0.18188567 0.11825548 0.18188567 0.18188567
[13] 0.12372201 0.17193932 0.18188567 0.18188567 0.18188567 0.18188567 0.18188567 0.17193932 0.12996184 0.01811433 0.12996184 0.07627799
[25] 0.01811433 0.01811433 0.01811433 0.01811433 0.01811433 0.08174452 0.01811433 0.01811433 0.07627799 0.02806068 0.01811433 0.01811433
[37] 0.01811433 0.01811433 0.01811433 0.02806068
有没有不使用 for 循环的快速方法?我正在尝试使用lapply,但它给了我一个错误。
> lapply(input, FUN = myfun, newdata = newdata, rate = rate)
Error in UseMethod("predict") :
no applicable method for 'predict' applied to an object of class "c('integer', 'numeric')"
此外,我不确定lapply 是否适合在这里使用。我认为通过使用lapply,它会将input[[1]]、input[[2]] 和input[[3]] 传递到myfun。但是,我想传入input[1]、input[1:2] 和input[1:3]。
在这个玩具示例中,input 是 3 个 rpart 对象的列表。但是,如果 input 是 100 个 rpart 对象的列表,我想避免使用 for 循环,因为那样效率很低。
【问题讨论】:
标签: r list loops vectorization lapply