Output of a function in R with a list (lda model, ggplot, dataframe)

84 Views Asked by At

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 dataframe
  • model: this is the lda information
  • ggplot_fun: this is the ggplot image

I tried:

  • as.list(model, pred, ggplot_fun) -> unsuccessful
  • list(model, pred, ggplot_fun) -> unsuccessful
  • x <- as.list(model, pred, ggplot_fun); return(x) -> unsuccessful
  • x <- 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
1

There are 1 best solutions below

0
antecessor On

I finally solved the issue. In order to give the answer to others with the same questions I changed the last line of the example:

list(model, pred, ggplot_fun)

By this one

list(LDA = model, Prediction = pred, Ggplot = ggplot_fun)

Basically I named each of the elements.