rdataframeggplot2

saving the results of a function in a data frame that returns counts and ggplot


I wrote a function that returns me a list containing a number (odchylka.sr) and a ggplot object (ggpl)

model.ARIMA.RF.fct <- function (l.obs.pomin) { 

  ...
  wynik.lst <- list (odchylka.sr, ggpl)
  return(wynik.lst)

}

I save the results in a data frame according to

ARIMA.RF.cwu.wyniki <- data.frame(
  l.obs.pomin = c(52, 69, 136, 217)
  ) %>% 
  mutate(
    out = pmap(list (l.obs.pomin), model.ARIMA.RF.fct)
  )

I receive

enter image description here

I want the odchylka.sr to be a separate column before the 'out' column.

I can't cope with this task.

I use pmap because my target function has 3 arguments.

When I use the solution from unnest:

ARIMA.RF.cwu.wyniki <- data.frame(
  l.obs.pomin = c(52, 69, 136, 217)
  ) %>% 
  mutate(
    out = pmap(list (l.obs.pomin), model.ARIMA.RF.fct)
  )|> unnest(out) 

I get a result close to what I expected, but I can't convert it to wide format

enter image description here


Solution

  • 
    library(tidyverse)
    function_that_returns_lists <- function(x){
      thing_2 <- ggplot () +
        geom_point(aes (x = c(1,2,3), y = c(18,5,2)))
      
      tibble(thing_1 = x+1,
           thing_2 = list(thing_2)) # properly wrap the outputs for a tibble container ggplots must be in lists
    }
    
    df1 <- tibble(
      l.obs.pomin = c(52, 69, 136, 217)
    ) %>% 
      mutate(
        out = pmap_df(list (l.obs.pomin), function_that_returns_lists) # pmap_df so out is more conveniently structured
      ) |> unnest(out)