5

I have the following example data frame:

library(tibble)
library(tidyverse)
df <- tibble(A = 1, B = 1)
df2 <- tibble(C = 2:4, D = 4:6)
df <- df %>%
        nest(B) %>%
        mutate(data = map(data, ~df2))

It's a nested 3x2 data frame (df2) in a 1x2 data frame (df). Is there a way to combine purrr::map and dplyr::select to select only column C in the nested data frame? I'm hoping to avoid unnest. The outcome should be:

      A             data
  <dbl>           <list>
1     1 <tibble [3 x 1]>
2
  • 2
    I may be unclear on what you want to do. Does mutate(data = map(data, ~select(df2, "C"))) do what you want?
    – aosmith
    Jun 30, 2017 at 18:22
  • Yes, it's the right outcome, but your code uses df2 and not df. I'd like a solution that uses data column of df only. I've provided a toy example, but in my actual case, it's easier if I try to select columns from within the nested data.frame.
    – CPak
    Jun 30, 2017 at 18:29

1 Answer 1

8

Once you've made the nested dataset that you have, you can use select in map on the "data" column in the same mutate call.

df %>%
    nest(B) %>%
    mutate(data = map(data, ~df2),
           data = map(data, ~select(.x, "C") ) )
1
  • Thanks for the help!
    – CPak
    Jun 30, 2017 at 18:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.