Get the min of two columns
Asked Answered
C

3

36

I want to get the minimum of two columns and create a column in the same data.frame. How can I do that?

For example:

ID    Parm1   Parm2
 1      1       2
 2      0       1
 3      2       1
 4      1       0
 5      2       0

Desired output :

ID    Parm1    Parm2     Min
 1      1        2        1
 2      0        1        0
 3      2        1        1
 4      1        0        0
 5      2        0        0
Confraternity answered 24/2, 2014 at 1:35 Comment(1)
data$Min <- with(data, pmin(Parm1, Parm2))Manslayer
H
42

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
Hayrack answered 24/2, 2014 at 1:49 Comment(4)
And do.call(pmin, dat[-1]) if you have a host of variables and just want to exclude the first ID variable and save typing.Madcap
Thanks all for the answer ^_^Confraternity
Today I learned this. I was using some very inefficient way to do this till now. thanks a lot.Mammilla
Hi Gavin, what if I require pmin but ignore 0?Kudva
C
16

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)

Chauvinism answered 15/11, 2020 at 9:27 Comment(1)
If there are many columns and you just want to exclude column ID variable, similar to the proposal in comment by @thelatemail, use dat %>% rowwise() %>% mutate(min = min(c_across(!ID))) and save typing.Belga
V
8

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

Vein answered 1/4, 2020 at 12:16 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.