Get the min of two columns

You want the parallel minimum implemented in function pmin(). For example using your data:

dat <- read.table(text = "ID    Parm1   Parm2
 1      1       2
 2      0       1
 3      2       1
 4      1       0
 5      2       0", header = TRUE)

you can use transform() to add the min column as the output of pmin(Parm1, Parm2) and access the elements of dat without indexing:

dat <- transform(dat, min = pmin(Parm1, Parm2))

This gives:

> dat
  ID Parm1 Parm2 min
1  1     1     2   1
2  2     0     1   0
3  3     2     1   1
4  4     1     0   0
5  5     2     0   0

In data.table way: dat [, min := pmin(Parm1, Parm2)]


In tidyverse universe, using dplyr package:

library(dplyr)

dat <- read.table(text = "ID    Parm1   Parm2
 1      1       2
 2      0       1
 3      2       1
 4      1       0
 5      2       0", header = TRUE)

dat %>% 
  rowwise() %>%
  mutate(min = min(Parm1, Parm2))
#> # A tibble: 5 x 4
#> # Rowwise: 
#>      ID Parm1 Parm2   min
#>   <int> <int> <int> <int>
#> 1     1     1     2     1
#> 2     2     0     1     0
#> 3     3     2     1     1
#> 4     4     1     0     0
#> 5     5     2     0     0

Created on 2020-11-15 by the reprex package (v0.3.0)

Tags:

R