R过滤以删除地图功能中的行

问题描述 投票:2回答:2

我使用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功能呢?这将使我的代码的内存占用更容易管理。谢谢!

r dictionary filter purrr
2个回答
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

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

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
© www.soinside.com 2019 - 2024. All rights reserved.