Reputation: 67
I have a data frame, where I would like to get the corresponding values the min value.
library(data.table)
df <- data.frame(cbind(c(1,1,1,1,2,2,2,2),
c(180,170,180,190,160,170,170,180),
c(80,75,76,81,67,65,66,70),
c(5,6,7,8,9,5,6,7)
))
df_stat <- setDT(df)[, list(
min = min(X2)
), by = X1]
The outcome should be looking like
df_stat <- data.frame(cbind(c(1,2),
c(170,160),
c(75,67),
c(6,9)
))
I have tried with which.min and others but they did not provide the right result. Thanks in advance. Eric
Upvotes: 2
Views: 99
Reputation: 92282
You can use .SD
on your original data
setDT(df)
df[, .SD[which.min(X2)], by = X1]
# X1 X2 X3 X4
# 1: 1 170 75 6
# 2: 2 160 67 9
Or you could sort by X1
and X2
and select unique X1
unique(setorder(df, X1, X2), by = "X1")
# X1 X2 X3 X4
# 1: 1 170 75 6
# 2: 2 160 67 9
Or create an index using .I
and then subset by it
indx <- df[, .I[which.min(X2)], by = X1]$V1
df[indx]
# X1 X2 X3 X4
# 1: 1 170 75 6
# 2: 2 160 67 9
Upvotes: 4