【问题标题】:Using functions with map in nested data frames在嵌套数据框中使用带有地图的函数
【发布时间】:2021-05-24 14:00:11
【问题描述】:

我有一个包含 13 个组的嵌套数据框,每个组在数据列中包含 3 个变量。我想用唯一的unhashed_id来消除观察,如下。

.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)

我如何使用 map 为所有 14 个组执行此操作,而不是重复此过程 14 次?

这是我的未嵌套数据:

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"))

我将这些数据嵌套如下:

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

有 13 个geo_id 组。在每个组中,我想删除 unhashed_id 只出现一次的观察结果。

抱歉,我是论坛的新手,正在学习论坛礼仪。谢谢!

【问题讨论】:

  • 如果您通过 dput(head(data)) 分享可重现的数据片段,您将更有可能获得相关解决方案,以便我们更清楚地了解您的数据结构是什么样的。
  • 感谢 Anoushiravan!我还在学习,所以感谢提示:)

标签: r purrr


【解决方案1】:

这是一个开始的解决方案,我建议不要 nesting 你的数据集,而是 group_split 它然后 bind_row 你的所有子集:

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

或者,如果您想坚持自己的解决方案,这也是一个很好的解决方案,您可以使用:

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

【讨论】:

  • 非常感谢!这就像魔术一样。
  • 这是我的荣幸。很高兴它对您有所帮助。
猜你喜欢
  • 1970-01-01
  • 2018-04-20
  • 1970-01-01
  • 2019-11-27
  • 2018-08-12
  • 2018-03-21
  • 1970-01-01
  • 2018-10-17
  • 1970-01-01
相关资源
最近更新 更多