How to use Dplyr's Summarize and which() to lookup min/max values

后端 未结 3 2019
我寻月下人不归
我寻月下人不归 2020-12-06 04:33

I have the following data:

Name <- c(\"Sam\", \"Sarah\", \"Jim\", \"Fred\", \"James\", \"Sally\", \"Andrew\", \"John\", \"Mairin\", \"Kate\", \"Sasha\", \         


        
3条回答
  •  青春惊慌失措
    2020-12-06 05:19

    I would actually recommend keeping your data in a "long" format. Here's how I would approach this:

    library(dplyr)
    

    Keeping all values when there are ties:

    data %>%
      group_by(Group) %>%
      arrange(Age) %>%  ## optional
      filter(Age %in% range(Age))
    # Source: local data frame [8 x 3]
    # Groups: Group
    # 
    #     Name Age Group
    # 1    Sam  22     A
    # 2  Sarah  31     B
    # 3    Jim  31     B
    # 4  James  58     B
    # 5 Andrew  17     C
    # 6  Sally  82     C
    # 7 Mairin  12     D
    # 8    Ray  67     D
    

    Keeping only one value when there are ties:

    data %>%
      group_by(Group) %>%
      arrange(Age) %>%
      slice(if (length(Age) == 1) 1 else c(1, n())) ## maybe overkill?
    # Source: local data frame [7 x 3]
    # Groups: Group
    # 
    #     Name Age Group
    # 1    Sam  22     A
    # 2  Sarah  31     B
    # 3  James  58     B
    # 4 Andrew  17     C
    # 5  Sally  82     C
    # 6 Mairin  12     D
    # 7    Ray  67     D
    

    If you really want a "wide" dataset, the basic concept would be to gather and spread the data, using "tidyr":

    library(dplyr)
    library(tidyr)
    
    data %>%
      group_by(Group) %>%
      arrange(Age) %>%
      slice(c(1, n())) %>%
      mutate(minmax = c("min", "max")) %>%
      gather(var, val, Name:Age) %>%
      unite(key, minmax, var) %>%
      spread(key, val)
    # Source: local data frame [4 x 5]
    # 
    #   Group max_Age max_Name min_Age min_Name
    # 1     A      22      Sam      22      Sam
    # 2     B      58    James      31    Sarah
    # 3     C      82    Sally      17   Andrew
    # 4     D      67      Ray      12   Mairin
    

    Though what wide form you would want with ties is unclear.

提交回复
热议问题