Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding maximum value for column among a subset of a data frame

Tags:

r

Given a data frame df with columns d, c, v. How do I find the value of d for the maximum value of v among the subset of records where c == "foo"?

I tried this:

df[df$v==max(df$v) & df$c == "foo","d"]

But I got:

character(0)
like image 999
amh Avatar asked Dec 28 '22 02:12

amh


1 Answers

Yo can do as follows:

with(df, d[v== max(v[c=="foo"])])

EDITED: If you want to get the value of d for all the levels of c:

library(plyr)
ddply(df, "c", subset, v==max(v))
like image 121
Manuel Ramón Avatar answered Jan 31 '23 00:01

Manuel Ramón