Reputation: 13
I have a data frame like this:
X Y
1 2
3 1
1 1
2 3
1 2
Now I want to find the minimum value of X and among the smallest values for X I want to pick the row that has the smallest value for Y. (My data has several minima.) So in this example the desired output is "line 3" because minimum value of X is 1 and among the rows with X=1 the minimum value for Y is in line 3 (Y=1). I know the function min() which seems to pick the first minimal value of the data.frame or of the specified column of the data.frame.
But is there a function in R or an easy way to find the row that minimizes X and Y at the same time?
Right now I would
But there must be a more easy way to do it?
Upvotes: 0
Views: 528
Reputation: 101034
Another base R option
> df[which.min(as.integer(interaction(df))), ]
X Y
3 1 1
or a data.table
option
> setorder(setDT(df))[1]
X Y
1: 1 1
Upvotes: 0
Reputation: 1241
use data.table
package
library(dplyr)
library(data.table)
dt <- read.table(text = "X Y
1 2
3 1
1 1
2 3
1 2", header = T)
dt <- dt %>% as.data.table() ## convert to data.table
dt[X == min(X), .SD[Y == min(Y)]][1]
Upvotes: 0
Reputation: 388797
If you arrange the data by X
and Y
, you can select the 1st row of the dataframe.
In dplyr
that would be -
library(dplyr)
df %>% arrange(X, Y) %>% slice(1L)
# X Y
#1 1 1
Or in base R -
df[order(df$X, df$Y)[1], ]
Upvotes: 2