I am building some regression tree models, I have done everything, now I want to write the trees to a pdf file. I am using below command to generate it.
pdf(file=paste0("Plots1.pdf"), header= "Rpart Outcome" )
lapply(names(tree.2), function(x)fancyRpartPlot(tree.2[[x]]))
dev.off()
The tree.2 object contains 8 different models of rpart
and it is saved as a list.
The above command works like a charm but the problem is that I want a separate header on top of every page of PDF as per the names of the list tree.2 (names(tree.2)
), I have tried lot of different permutation and combination but unable to solve it via lapply
, However if I use a for loop
the above thing is achievable. I want to use lapply
to perform this, Is it possible? I know it is, but I am not able to do it for now.
Libraries used here: rattle
, rpart
Toy example:
tree1 <- rpart(as.formula(mpg ~ hp + wt), data=mtcars)
tree2 <- rpart(as.formula(mpg ~ am + hp), data=mtcars)
treex <- list("tree1"= tree1, "tree2"=tree2)
pdf(file="file.pdf", header="Rpart Outcome")
lapply(names(treex), function(x)fancyRpartPlot(treex[[x]]))
dev.off()
Here, I want header on every page basis names(treex).
Please let me know in case if its a duplicate question (haven't found one), I will remove immediately.
Thanks
This seems to work for me:
library(rpart)
library(rattle)
tree1 <- rpart(as.formula(mpg ~ hp + wt), data=mtcars)
tree2 <- rpart(as.formula(mpg ~ am + hp), data=mtcars)
treex <- list("tree1"= tree1, "tree2"=tree2)
pdf(file="file.pdf")#, header="Rpart Outcome")
lapply(names(treex), function(x)fancyRpartPlot(treex[[x]], main = x))
dev.off()
I have just added an argument main
in the fancyRpartPlot
which takes the name of the plot.
Hope it helps!