erc
erc

Reputation: 10123

how to use which.min in subset of data frame?

I have this data frame

df <- structure(list(a = 1:20, b = c(4, 2, 5, 6, 2, 4, 7, 4, 9, 7, 6, 1, 1, 5, 2, 1, 9, 8, 6, 3), c = c(340, 200, 130, 730, 710, 340, 200, 130, 730, 710, 340, 200, 130, 730, 710, 340, 200, 130, 730, 710)), .Names = c("a", "b", "c"), row.names = c(NA, -20L), class = "data.frame")

My desired output is the index of

which.min(df[1:V,3])

where V is a row number, e.g.

V <- 10

However, I'd like the following restriction:

df[which(df$a<=df$b[V]),]

I think I've tried any combinition to bring these together (e.g. with with()) but I just cannot get it to work. What do I have to do?

Upvotes: 0

Views: 988

Answers (2)

eddi
eddi

Reputation: 49448

Using data.table instead of data.frame this can be represented in a much more readable way:

library(data.table)
dt = as.data.table(df)

dt[a <= b[V]][1:V, which.min(c)]
#[1] 3

Upvotes: 1

talat
talat

Reputation: 70256

Is this what you are looking for?

which.min(with(df, df[a<=b[V],])[1:V,3])
#[1] 3

Upvotes: 1

Related Questions