Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find MIN value of 3 Columns for Each Row in R

Tags:

r

min

I have a dataframe, like the below:

ID      D1          D2          D3
103     2015-01-15  2014-06-10  2015-04-13
450     NA          2015-10-03  2014-02-02  
103     NA          NA          NA          
222     2014-03-03  NA          NA     

I need to add a column 5 called "MinDate", returning the minimum value for three different dates in R that are in columns 2 through 4 while ignoring NA values (although, if all are NA, then returning NA is okay), e.g. below:

ID      D1          D2          D3          MinDate
103     2015-01-15  2014-06-10  2015-04-13  2014-06-10
450     NA          2015-10-03  2014-02-02  2014-02-02
103     NA          NA          NA          NA
222     2014-03-03  NA          NA          2014-03-03

I could probably build a big nasty ifelse statement, but I would prefer to utilize the power and base capabilities of R,... I'm just not sure how. I am getting close using something like:

df$MinDate <- apply(df, 1, min, na.rm = TRUE)

But it is including the ID column.

like image 932
stevenjoe Avatar asked Sep 14 '25 15:09

stevenjoe


1 Answers

I think I got it:

df$MinDate <- apply(df[,c(2:4)], 1, min, na.rm = TRUE)
like image 181
stevenjoe Avatar answered Sep 16 '25 03:09

stevenjoe