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

后端 未结 3 2014
我寻月下人不归
我寻月下人不归 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:23

    You can use which.min and which.max to get the first value.

    data %>% group_by(Group) %>%
      summarize(minAge = min(Age), minAgeName = Name[which.min(Age)], 
                maxAge = max(Age), maxAgeName = Name[which.max(Age)])
    

    To get all values, use e.g. paste with an appropriate collapse argument.

    data %>% group_by(Group) %>%
      summarize(minAge = min(Age), minAgeName = paste(Name[which(Age == min(Age))], collapse = ", "), 
                maxAge = max(Age), maxAgeName = paste(Name[which(Age == max(Age))], collapse = ", "))
    

提交回复
热议问题