【问题标题】:Filtering out nested data frames by number of observations按观察次数过滤嵌套数据框
【发布时间】:2018-05-13 10:24:52
【问题描述】:

来自:Use filter() (and other dplyr functions) inside nested data frames with map()

我想嵌套在多列上,然后按嵌套在该行中的项目数过滤掉行。例如,

df <- tibble(
  a = sample(x = c(rep(c('x','y'),4), 'w', 'z')),
  b = sample(c(1:10)),
  c = sample(c(91:100))
)

我想嵌套在a列上,如:

df_nest <- df %>% 
nest(-a)

然后,我想过滤掉数据列中只有 1 个观察值的行(在本例中为 a = w 或 a = z)。我该怎么做?

【问题讨论】:

    标签: r dataframe nested dplyr tidyverse


    【解决方案1】:

    您可以在data 列上使用map/map_int 来返回每个嵌套tibble 中的nrow,并根据它构造过滤条件:

    df %>% 
        nest(-a) %>% 
        filter(map_int(data, nrow) == 1)
    #   filter(map(data, nrow) == 1)        works as well
    
    # A tibble: 2 x 2
    #      a             data
    #  <chr>           <list>
    #1     w <tibble [1 x 2]>
    #2     z <tibble [1 x 2]>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-11-20
      • 2019-05-02
      • 1970-01-01
      • 1970-01-01
      • 2017-04-05
      • 2023-03-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多