Reputation: 306
I have a function that transforms tibbles stored inside lists store inside a tibble. This is because do
function does that when used.
I then apply a function that filters out certain observations.
However, this function returns a tibble and not a list, so it is stored as a tibble inside the tibble instead of a list.
library(dplyr)
data(iris)
# Store observations in a list for this example
iris <- iris %>%
group_by(Species) %>%
do(obs = list(.$Sepal.Length))
iris$n <- 1:3
# The function that filters data
filter_fun <- function(x, n){
if(any(n > 2)){x <- filter(as_tibble(as.data.frame(x)), x > 2)
} else {x <- x}
return(x)}
# This makes two lists and a tibble inside a tibble instead of three lists
x <- iris %>%
group_by(Species) %>%
do(filtered = filter_fun(x = .$obs, n = .$n))
x
shows three elements in the second column, <list [1]>
, <list [1]>
and <tibble [0 x 1]>
when applied to iris
data. All of them should be lists. How do I change the tibble inside the tibble to a list that holds a tibble?
Upvotes: 2
Views: 456
Reputation: 887118
If we need a list
, then wrap the output of tibble
in a list
in the function
filter_fun <- function(x, n){
if(any(n > 2)){
filter(as_tibble(as.data.frame(x)), x > 2 ) %>% list(.)
} else x
}
Upvotes: 2