【问题标题】:How to get the first row that appears first in the data?如何获取数据中首先出现的第一行?
【发布时间】:2019-11-02 00:59:44
【问题描述】:

我有一个如下所示的数据集:

data <- tribble(
  ~shop_name, ~products, ~category_name,
  "A",         1,          "Game",
  "A",         1,          "Book",         
  "A",         2,          "Electronic",
  "A",         3,          "Home", 
  "B",         5,          "Game",
  "B",         5,          "Electronic",
  "B",         8,          "Home",
  "C",         1,          "Book",
  "C",         7,          "Game",
  "C",         9,          "Game",
)

我想查看基于产品的前 1 个类别,并编码:

data %>% 
  group_by(shop_name) %>% 
  top_n(1, products) %>% 
  mutate(top_category = toString(category_name))

但由于产品有时每个 shop_name 具有相同的值,因此“top_category”中有多个类别名称。如何获取数据集中最先出现的第一行?

【问题讨论】:

    标签: r dplyr


    【解决方案1】:

    使用dplyr::first:

    data %>% 
      group_by(shop_name) %>% 
      summarise(products = first(products),
                category_name = first(category_name))
    

    保留所有列而不明确指定它们

    data %>% 
      group_by(shop_name) %>% 
      summarise_all(first)
    

    输出

    # shop_name products category_name
    #  <chr>        <dbl> <chr>        
    # 1 A                1 Game         
    # 2 B                5 Game         
    # 3 C                1 Book 
    

    【讨论】:

    • 感谢您的评论。但我的列比我共享的数据多。有什么方法可以保留其他列吗?
    • 嗯,你的意思是我应该这样编码吗?数据 %>% group_by(shop_name) %>% summarise(products = first(products), category_name = first(category_name)) %>% summarise_all(first)
    • 使用第二个代码块:data %&gt;% group_by(shop_name) %&gt;% summarise_all(first)
    【解决方案2】:
    data %>% 
      group_by(shop_name) %>% 
      top_n(1, desc(products)) %>%
      plyr::ddply( "shop_name", head, 1)
    
      shop_name products category_name
    1         A        1          Game
    2         B        5          Game
    3         C        1          Book
    

    【讨论】:

      猜你喜欢
      • 2021-12-01
      • 1970-01-01
      • 2023-01-23
      • 1970-01-01
      • 1970-01-01
      • 2020-02-02
      • 2022-11-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多