How to access/select nested data frame column with dplyr

Viewed 327

I have the following data frame:

library(tidyverse)
iris %>% 
  dplyr::select(Species, Petal.Width) %>% 
  as_tibble() 

Then I group by Species to get mean_se with the following line of code:

df <- iris %>% 
  dplyr::select(Species, Petal.Width) %>% 
  as_tibble() %>%
  group_by(Species) %>% 
  mutate(ms = mean_se(Petal.Width))

It looks like this:

 df
# A tibble: 150 x 3
# Groups:   Species [3]
   Species Petal.Width  ms$y $ymin $ymax
   <fct>         <dbl> <dbl> <dbl> <dbl>
 1 setosa          0.2 0.246 0.231 0.261
 2 setosa          0.2 0.246 0.231 0.261
 3 setosa          0.2 0.246 0.231 0.261
 4 setosa          0.2 0.246 0.231 0.261
 5 setosa          0.2 0.246 0.231 0.261
 6 setosa          0.4 0.246 0.231 0.261
 7 setosa          0.3 0.246 0.231 0.261
 8 setosa          0.2 0.246 0.231 0.261
 9 setosa          0.2 0.246 0.231 0.261
10 setosa          0.1 0.246 0.231 0.261

However when I want to select ms$y and $ymax column, like this

> df %>% dplyr::select(Species, ms$y, $ymax)
Error: unexpected '$' in "df %>% dplyr::select(Species, ms$y, $"

It fails. What's the way to do it?

1 Answers

It gets stored as a nested dataframe. You can convert it to normal dataframe as :

library(tidyverse)

iris %>% 
  select(Species, Petal.Width) %>% 
  as_tibble() %>%
  group_by(Species) %>% 
  mutate(ms = mean_se(Petal.Width)) %>%
  ungroup -> tmp

df <- bind_cols(tmp %>% select(-ms), tmp$ms) 
df

# A tibble: 150 x 5
#   Species Petal.Width     y  ymin  ymax
#   <fct>         <dbl> <dbl> <dbl> <dbl>
# 1 setosa          0.2 0.246 0.231 0.261
# 2 setosa          0.2 0.246 0.231 0.261
# 3 setosa          0.2 0.246 0.231 0.261
# 4 setosa          0.2 0.246 0.231 0.261
# 5 setosa          0.2 0.246 0.231 0.261
# 6 setosa          0.4 0.246 0.231 0.261
# 7 setosa          0.3 0.246 0.231 0.261
# 8 setosa          0.2 0.246 0.231 0.261
# 9 setosa          0.2 0.246 0.231 0.261
#10 setosa          0.1 0.246 0.231 0.261
# … with 140 more rows

Select the columns you need.

df %>% select(Species, y, ymax)

# A tibble: 150 x 3
#   Species     y  ymax
#   <fct>   <dbl> <dbl>
# 1 setosa  0.246 0.261
# 2 setosa  0.246 0.261
# 3 setosa  0.246 0.261
# 4 setosa  0.246 0.261
# 5 setosa  0.246 0.261
# 6 setosa  0.246 0.261
# 7 setosa  0.246 0.261
# 8 setosa  0.246 0.261
# 9 setosa  0.246 0.261
#10 setosa  0.246 0.261
# … with 140 more rows

Another way without creating temporary variable tmp would be :

iris %>% 
  select(Species, Petal.Width) %>% 
  as_tibble() %>%
  group_by(Species) %>% 
  mutate(ms = list(mean_se(Petal.Width))) %>%
  unnest(ms) %>%
  ungroup
Related