How to name the nesting column when using `tidyr::nest` with a grouped tibble?

Since tidyr v1, the .key argument in tidyr::nest has been deprecated in favour of a new syntax. For example this will nest columns y and z in a new list column named blah:

tibble(x = c(1,1,2,2), y = 1:4, z = 5:8) %>% 
nest(blah = c(y, z))

# A tibble: 2 x 2
# Groups:   x [2]
      x           blah
  <dbl> <list<df[,2]>>
1     1        [2 × 2]
2     2        [2 × 2]

However how do you name the nesting column when using nest with a grouped tibble? The only way I found is using dplyr::rename:

tibble(x = c(1,1,2,2), y = 1:4, z = 5:8) %>% 
group_by(x) %>%
nest %>%
rename(blah = data)

# A tibble: 2 x 2
# Groups:   x [2]
      x           blah
  <dbl> <list<df[,2]>>
1     1        [2 × 2]
2     2        [2 × 2]

However this will not work if there is already a column named data before the nesting (then nest will rename the former to data...1, and the new nesting column to data...2):

tibble(data = c(1,1,2,2), y = 1:4, z = 5:8) %>% 
group_by(data) %>%
nest 

New names:
* data -> data...1
* data -> data...2
# A tibble: 2 x 2
  data...1       data...2
     <dbl> <list<df[,2]>>
1        1        [2 × 2]
2        2        [2 × 2]

What is the proper way to specify the name of the nesting column in nest when using a grouped tibble as input?

1 Like

Hi @jerome

Does this work for your purposes?

tibble(x = c(1,1,2,2), y = 1:4, z = 5:8) %>% 
  group_nest(x, .key = 'blah')
3 Likes

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.