I am struggling on how to get an output of a function in R I am creating with a list of elements. Apparently it is simple, however, I cannot get into that. I checked different questions in SO but no result. This might be an easy question and probably I am misprinting some line.
The output of the function I am creating has three elements that I think they should be included in a list:
- Linear discriminant analysis model (lda).
- A dataframe
- A ggplot image
This is the version of the function I am working with:
fun <- function(data, tooth_type = c("m1", "m2", "m3"), position = c("U", "L")) {
model <- lda(Species ~ MD + BL, data = data)
# extract the information of the tooth we are working from the Omo database
tooth <- omo_numeric_mdbl[omo_numeric_mdbl$Tooth == tooth_type & omo_numeric_mdbl$Position == position, ]
tooth <- tooth[complete.cases(tooth[, 31:32]), ]
predictions <- model %>%
predict(tooth)
pred <- as.data.frame(predictions$posterior)*100
# plot
lda.data <- cbind(data, predict(model)$x)
ggplot_fun <- ggplot(lda.data, aes(LD1, LD2)) +
geom_point(aes(color = Species))
list(model, pred, ggplot_fun)
}
As you can see, inside the function there are three objects I would like to store:
pred
: this is the dataframemodel
: this is the lda informationggplot_fun
: this is the ggplot image
I tried:
as.list(model, pred, ggplot_fun)
-> unsuccessfullist(model, pred, ggplot_fun)
-> unsuccessfulx <- as.list(model, pred, ggplot_fun); return(x)
-> unsuccessfulx <- list(model, pred, ggplot_fun); return(x)
-> unsuccessful
Ultimately, what I would like is:
x <- fun(data, "m3", "L") # for example
x$pred # show the dataframe (and display as kable, if required)
x$model # show the lda model, and to get all the details inside as x$model$posterior
x$ggplot_fun # display the ggplot function