Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the min of two columns

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 
like image 512
Ianthe Avatar asked Feb 24 '14 01:02

Ianthe


People also ask

How do I find the minimum of two columns in SQL?

with ID/Col as the primary key (and possibly Col as an extra key, depending on your needs). Then your query becomes a simple select min(val) from tbl and you can still treat the individual 'old columns' separately by using where col = 2 in your other queries.

How do you find the minimum of a column in Python?

a) Find the minimum value among rows and columns :Dataframe. min() : This function returns the minimum of the values in the given object. If the input is a series, the method will return a scalar which will be the minimum of the values in the series.

How can I find the minimum value between two values in SQL Server?

To find the minimum value of a column, use the MIN() aggregate function; it takes as its argument the name of the column for which you want to find the minimum value. If you have not specified any other columns in the SELECT clause, the minimum will be calculated for all records in the table.


1 Answers

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 
like image 177
Gavin Simpson Avatar answered Oct 13 '22 20:10

Gavin Simpson