Lower Value of a Set of Columns

Asked

Viewed 182 times

3

I have a set of data and would like to select only the smallest value among each primary key. Follow the example of my DF:

ORDEM <- c(1,5,2,3,1,10)
GUIA <- c('111','111','333','333','555','555')
COR <- c('AZUL','AMARELO','PRETO','LARANJA','ROSA','VERDE')
DADOS <- data.frame(ORDEM,GUIA,COR)

In this example, there are two records for each key (GUIA). Therefore, I would like the result to appear only the lowest value from the column ORDEM. The result I expect should be:

ORDEM <- c(1,2,1)
GUIA <- c('111','333','555')
COR <- c('AZUL','PRETO','ROSA')
DADOS_FINAL <- data.frame(ORDEM,GUIA,COR)

1 answer

5


With dplyr you can do so:

library(dplyr)
DADOS %>%  group_by(GUIA) %>% filter(ORDEM == min(ORDEM)) %>% ungroup()
# A tibble: 3 x 3
  ORDEM GUIA  COR  
  <dbl> <fct> <fct>
1     1 111   AZUL 
2     2 333   PRETO
3     1 555   ROSA 

Browser other questions tagged

You are not signed in. Login or sign up in order to post.