【问题标题】:Filter list of distinct values from one column of grouped data in the same order as it shows以与显示的顺序相同的顺序从一列分组数据中过滤不同值的列表
【发布时间】:2021-03-04 14:53:02
【问题描述】:

我有一个按几个变量分组的数据集,并按其中一个变量降序排列。我想从一列中获取不同值的列表,按照它在分组和降序排序后出现在结果中的顺序。

这是一个示例数据集:

set.seed(42)
id    <- seq_len(10)
city  <- sample(c('Miami', 'Seattle', 'Houston', 'Toronto', 'Tokyo', 'Mumbai', 'Austin'), 10, replace = TRUE)
state <- sample(c('ON', 'WA', 'TX', 'MA'), 10, replace = TRUE)
rent  <- sample(800:1900, 10)

data = data.frame(id, city, state, rent)

我使用三列进行分组,并按降序对总租金进行排序,得到以下结果:

data %>% 
  group_by(id, city, state) %>% 
  summarise(total_rent = sum(rent)) %>% 
  arrange(desc(total_rent))

group_by result

现在,我想要按照上面结果中出现的顺序列出唯一城市值。 例如。

Houston
Toronto
Miami
Mumbai
Austin

我试过了:

  group_by(id, city, state) %>% 
  summarise(total_rent = sum(rent)) %>% 
  arrange(desc(total_rent)) %>% 
  slice_max(1) 

还有top_n()distinct(),但是没有用。我也看到 row_number()could 工作,但我找不到让它适合我的方法。

【问题讨论】:

    标签: r dplyr


    【解决方案1】:

    由于某种原因,完全无法重新创建您的数据,所以我的输出有所不同,但这里有一些快速的方法可以实现您想要的结果:

    对您的原始代码进行一些编辑,为我们提供了一个数据框,其中包含按正确顺序排列的正确城市:

    library(dplyr)
    
    set.seed(42)
    
    id    <- seq_len(10)
    city  <- sample(c('Miami', 'Seattle', 'Houston', 'Toronto', 'Tokyo', 'Mumbai', 'Austin'), 10, replace = TRUE)
    state <- sample(c('ON', 'WA', 'TX', 'MA'), 10, replace = TRUE)
    rent  <- sample(800:1900, 10)
    
    data  <- data.frame(id, city, state, rent)
    
    data %>% 
      group_by(id, city, state) %>% 
      summarise(total_rent = sum(rent)) %>% 
      group_by(city) %>% 
      slice_max(1) %>% 
      arrange(desc(total_rent)) %>% 
      ungroup()
    #> # A tibble: 5 x 4
    #>      id city    state total_rent
    #>   <int> <chr>   <chr>      <int>
    #> 1     1 Miami   MA          1698
    #> 2     6 Toronto WA          1659
    #> 3     5 Seattle ON          1420
    #> 4     2 Tokyo   TX          1400
    #> 5    10 Austin  TX          1098
    

    就值而言,pull() / unique() 组合非常好:

    data %>% 
      group_by(id, city, state) %>% 
      summarise(total_rent = sum(rent)) %>% 
      arrange(desc(total_rent)) %>% 
      pull(city) %>% 
      unique()
    #> [1] "Miami"   "Toronto" "Seattle" "Tokyo"   "Austin"
    

    另一种可能的解决方案可能是在您安排好城市之后按顺序分解它们。这是通过library(forecats) 实现的:

    library(forcats)
    library(magrittr)
    
    data %>% 
      group_by(id, city, state) %>% 
      summarise(total_rent = sum(rent)) %>% 
      arrange(desc(total_rent)) %>% 
      ungroup() %>% 
      mutate(city = fct_inorder(city)) %$% 
      levels(city) 
    #> [1] "Miami"   "Toronto" "Seattle" "Tokyo"   "Austin"
    

    reprex package (v0.3.0) 于 2021-03-04 创建

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多