1

I have read this question, and I cannot make sense of it in my case, where I have ggplots in my tibble.

Say I have:

library(tidyverse)
f <- function(n) {
  p <- tibble(x = rnorm(30, n)) %>%
    ggplot(aes(x = x)) + geom_density()
  return(list(n = n, p = p))
}
m <- map(seq(10), f)

I would like to turn m into a tibble, with ten rows and two columns, named n and p. I also would like my code to work with any number of columns, any type of column, if possible.

as_tibble(transpose(m)) gives me

# A tibble: 10 x 2
   n         p     
   <list>    <list>
 1 <int [1]> <gg>  
 2 <int [1]> <gg>  
 3 <int [1]> <gg>  
 ...

i.e. each cell is a list, with one element. I would like to transform each list to a scalar.

What I have tried:

  • I have used map_int for the column n, but what to do with column p?
  • unnest also work for column n, but not with p.
  • Same with unlist on the column p (even with recursive = FALSE).
Cettt
  • 11,460
  • 7
  • 35
  • 58
unamourdeswann
  • 445
  • 3
  • 14

1 Answers1

1

Here is one possibility. You modify the function such that it only returns the plot. Then you create the tibble with only column n and create column p using map.

f2 <- function(n) {
  tibble(x = rnorm(30, n)) %>%
    ggplot(aes(x = x)) + geom_density()
}

tibble(n = 1:10,
       p = map(n, f2))

Then column n is an integer. p is a list but this is the best you can get since columns of tibbles cannot contain objects of type gg or ggplot but only lists containing these objects.

As far as I know the only possible column types are: int, dbl, date, dttm, factor, logical, character and list.

Cettt
  • 11,460
  • 7
  • 35
  • 58
  • In real life, `f` computes lots of things, so I would not favour this solution. Could you please add a link to why `tibble`s cannot contain `gg`s? – unamourdeswann Oct 15 '19 at 08:10
  • 1
    Maybe chapter 3.6 of advanced R: https://adv-r.hadley.nz/vectors-chap.html – Cettt Oct 15 '19 at 08:22