问题描述
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,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],rate = rate)
第三个包含:
myfun(mod = input[1:3],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,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循环,因为这样效率很低。
解决方法
使用lapply
,您可以执行以下操作:
lapply(seq_along(input),function(x)
myfun(mod = input[seq_len(x)],newdata = newdata,rate = rate))
#[[1]]
#[1] 0
#[[2]]
# [1] 0.0279 0.0916 0.0279 0.0816 0.0916 0.0916 0.0916 0.0916 0.0916 0.0279
#[11] 0.0916 0.0916 0.0816 0.0816 0.0916 0.0916 0.0916 0.0916 0.0916 0.0816
#[21] 0.0721 0.0084 0.0721 0.0184 0.0084 0.0084 0.0084 0.0084 0.0084 0.0721
#[31] 0.0084 0.0084 0.0184 0.0184 0.0084 0.0084 0.0084 0.0084 0.0084 0.0184
#[[3]]
# [1] 0.070 0.182 0.070 0.124 0.182 0.182 0.182 0.182 0.182 0.118 0.182
#[12] 0.182 0.124 0.172 0.182 0.182 0.182 0.182 0.182 0.172 0.130 0.018
#[23] 0.130 0.076 0.018 0.018 0.018 0.018 0.018 0.082 0.018 0.018 0.076
#[34] 0.028 0.018 0.018 0.018 0.018 0.018 0.028