Reputation: 487
I have read this question, and I cannot make sense of it in my case, where I have ggplot
s 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:
map_int
for the column n
, but what to do with column p
?unnest
also work for column n
, but not with p
.unlist
on the column p
(even with recursive = FALSE
).Upvotes: 1
Views: 422
Reputation: 11981
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
.
Upvotes: 1