nest .key in dplyr deprecated, what to use instead

Viewed 286

In the recent dplyr version (1 <= ) the .key argument got deprecated.

In the docu they write that:

.key Deprecated lifecycle: No longer needed because of the new new_col = c(col1, col2, col3) syntax.

I do not use new_col syntax but the group_by (I do know the key column but col1, col2 etc might differ).

How do I change the code below so that it still does the same but does not produce the deprecated warning?

data <- data.frame(key= rep(letters,2), a = runif(2*length(letters)), b = runif(2*length(letters)))
data %>% group_by(key) %>% nest(.key="myData")
head(data)

2 Answers

In nest , now you need to specify the columns which you want to turn into list.

library(dplyr)
library(tidyr)

data %>% group_by(key) %>% nest(myData = c(a, b))

#   key   myData          
#   <chr> <list>          
# 1 a     <tibble [2 × 2]>
# 2 b     <tibble [2 × 2]>
# 3 c     <tibble [2 × 2]>
# 4 d     <tibble [2 × 2]>
# 5 e     <tibble [2 × 2]>
# 6 f     <tibble [2 × 2]>
# 7 g     <tibble [2 × 2]>
# 8 h     <tibble [2 × 2]>
# 9 i     <tibble [2 × 2]>
#10 j     <tibble [2 × 2]>
# … with 16 more rows

Or remove the columns which you don't want to turn into a list :

data %>% group_by(key) %>% nest(myData = -key)

However, I don't know why they deprecated .key in nest and replaced it in another new function nest_by which works the same.

data %>% group_by(key) %>% nest_by(.key="myData")
#OR
#data %>% nest_by(key, .key="myData")

We don't have to specify each column name. An easier option is with group_cols

library(tidyr)
library(dplyr)
data %>% 
    group_by(key) %>%
    nest(my_data = -group_cols())
# A tibble: 26 x 2
# Groups:   key [26]
#   key   my_data         
#   <chr> <list>          
# 1 a     <tibble [2 × 2]>
# 2 b     <tibble [2 × 2]>
# 3 c     <tibble [2 × 2]>
# 4 d     <tibble [2 × 2]>
# 5 e     <tibble [2 × 2]>
# 6 f     <tibble [2 × 2]>
# 7 g     <tibble [2 × 2]>
# 8 h     <tibble [2 × 2]>
# 9 i     <tibble [2 × 2]>
#10 j     <tibble [2 × 2]>
# … with 16 more rows
Related