Search code examples
rdataframeminimum

Choose lowest value in each row R


I have the df below.

     Postcode    A      B      C        D      E

 1     4251     45.8   55.1   70.2     79.5    102  
 2     4254     41.7   51.0   66.1     75.3    97.9  
 3     4255     45.5   48.7   63.9     73.1    95.6  
 4     4681     114    100    96.4     102     125   

I want the minimum value of each row where postcode is not a number but a character.

expected output:

  Postcode   Dis  Location
1  4251      45.8   A
2  4254      41.7   A
3  4255      45.5   A
4  4681      96.4   C

Solution

  • library(dplyr)
    library(tidyr)
    
    df |>
      pivot_longer(cols = A:E, names_to = "Location", values_to = "Dis") |>
      group_by(Postcode) |>
      filter(Dis == min(Dis))
      
    
    + # A tibble: 4 × 3
    # Groups:   Postcode [4]
      Postcode Location   Dis
      <chr>    <chr>    <dbl>
    1 4251     A         45.8
    2 4254     A         41.7
    3 4255     A         45.5
    4 4681     C         96.4