R筛选以删除地图功能中的行

时间:2019-04-07 01:27:52

标签: r dictionary filter purrr

我正在使用data函数模拟以下map表中的事件并过滤zero值事件。

但是我想在map函数中进行过滤,从而减小创建的event表的大小。

以下代码基于给定均值的泊松分布模拟events(它包括freq = 0,但是为了管理内存,我不希望使用这些变量)

library(tidyverse)
set.seed(1); n <- 10
data <- tibble(locid = seq(5), exp = 2)

event <- data %>% 
    mutate(freq = map(exp, ~rpois(n, .x))) %>%
    mutate(freq = map(freq, ~ data.frame(freq = .x, sim = seq_along(.x)))) %>%
    unnest()

然后我可以使用event %>% filter(freq != 0)进行过滤。请问如何将其插入map函数中?这将使我的代码的内存占用量更易于管理。谢谢!

2 个答案:

答案 0 :(得分:2)

选项为discard

library(tidyverse)
data %>% 
    mutate(freq = map(exp, ~rpois(n, .x) %>%
                           discard(. == 0) %>%
                           tibble(freq = ., sim = seq_along(.)))) %>% 
    unnest

如果“ sim”应基于原始序列,则创建“ rpois”输出的tibble和元素序列,然后在filter内执行map < / p>

data %>% 
    mutate(freq = map(exp, ~ rpois(n , .x)  %>% 
                               tibble(freq = ., sim = seq_along(.))  %>% 
                               filter(freq != 0))) %>%
    unnest

或在两者之间使用mutate

 data %>% 
     mutate(freq = map(exp, ~  tibble(freq = rpois(n, .x)) %>% 
                                  mutate(sim = row_number()) %>% 
                                  filter(freq != 0))) %>%
     unnest

答案 1 :(得分:2)

这是一个主意。无需创建data.frame。用listfreq创建sim,然后unnest

library(tidyverse)
set.seed(1); n <- 10
data <- tibble(locid = seq(5), exp = 2)

event <- data %>% 
  mutate(freq = map(exp, ~rpois(n, .x)),
         sim = map(freq, ~which(.x > 0)),
         freq = map(freq, ~.x[.x > 0]))%>%
  unnest()
event
# # A tibble: 45 x 4
#    locid   exp  freq   sim
#    <int> <dbl> <int> <int>
#  1     1     2     1     1
#  2     1     2     1     2
#  3     1     2     2     3
#  4     1     2     4     4
#  5     1     2     1     5
#  6     1     2     4     6
#  7     1     2     4     7
#  8     1     2     2     8
#  9     1     2     2     9
# 10     2     2     1     1
# # ... with 35 more rows