Using functions with map in nested data frames

Viewed 136

I have a nested data frame with 13 groups, each group containing 3 variables in the data column. I want to eliminate observations with a unique unhashed_id, as follows.

.x <- data_nest %>% pluck("data", 1) %>% group_by(unhashed_id) %>% filter(n()>1) %>% summarise(count=n()) %>% tally(count)
.x <- data_nest %>% pluck("data", 2) %>% group_by(unhashed_id) %>% filter(n()>1) %>% summarise(count=n()) %>% tally(count)

Rather than repeating this process 14 times, how do I use map to do this for all 14 groups?

Here is my unnested data:

structure(list(geo_id = c("Atlanta", "Atlanta", "Atlanta", "Atlanta", "Atlanta", 
"Atlanta"), unhashed_id = c("002A7B15-E6CC-4771-9415-87D8DCC901EF", 
"01CC2CB4-6161-4667-923B-C9CE8F231333", "01CC2CB4-6161-4667-923B-C9CE8F231333", 
"01EAE8A9-4448-4BE5-8629-716B77D8BBE6", "01ED5B91-42D7-48E6-8DA5-92BD3CF15CE3", 
"01ED5B91-42D7-48E6-8DA5-92BD3CF15CE3"), date = structure(c(18214, 
17943, 18069, 18054, 18090, 18216), class = "Date"), dwell_time = c(4923, 
18000, 17601, 14400, 5005, 18011)), row.names = c(NA, -6L), class = c("tbl_df", 
"tbl", "data.frame"))

I nest this data as follows:

data_poi_nest <- data_poi3 %>% group_by(geo_id) %>% nest()

There are 13 geo_id groups. In each group, I want to drop observations where unhashed_id appears only once.

Apologies, I am new at the forum and learning the forum etiquette. Thanks!

1 Answers

Here is a solution for the start, I suggest instead of nesting your data set, you group_split it and then bind_row all of your subsets:

library(dplyr)
library(purrr)


df2 %>% 
  group_split(geo_id) %>%
  map_dfr(~ .x %>% 
        group_by(unhashed_id) %>% 
          filter(n() > 1) %>% 
          summarise(count = n()) %>%
          tally(count)) 


# A tibble: 1 x 1
      n
  <int>
1     4

Or in case you want to stick by your own solution which is also a good one you can use this:

df2 %>% 
  group_by(geo_id) %>%
  nest() %>%
  mutate(data = map(data, ~ .x %>% 
                      group_by(unhashed_id) %>% 
                      filter(n() > 1) %>% 
                      summarise(count = n()) %>% 
                      tally(count))) %>%
  unnest(cols = data)

# A tibble: 1 x 2
# Groups:   geo_id [1]
  geo_id      n
  <chr>   <int>
1 Atlanta     4
Related