[R] Extract from data.frame

Bert Gunter bgunter.4567 at gmail.com
Mon Sep 21 20:03:56 CEST 2015


Note the following problems:

1. " max_row <- (1:nrow(df))[which.max(df$Amount)]"

This is a bit silly.

max_row <- which.max(df$Amount)


will do. See ?which.max


2. What happens if the max is the first or last row? e.g.

> dat <- data.frame(a=runif(5),b=1:5)
> max_row<- which.max(dat$b)
> mean(dat[max_row+c(-1,0,1),"b"]) ## 2-d indexing
[1] NA


Cheers,
Bert Gunter

"Data is not information. Information is not knowledge. And knowledge
is certainly not wisdom."
   -- Clifford Stoll


On Mon, Sep 21, 2015 at 10:51 AM, Mark Sharp <msharp at txbiomed.org> wrote:
> Nico,
>
> I expect there are many better ways to do this, but this does work:
> max_row <- (1:nrow(df))[which.max(df$Amount)]
> mean(df$Amount[max_row + c(-1, 0, 1)])
>
>> max_row <- (1:nrow(df))[which.max(df$Amount)]
>> mean(df$Amount[max_row + c(-1, 0, 1)])
> [1] 151.6667
>
> R. Mark Sharp, Ph.D.
> Director of Primate Records Database
> Southwest National Primate Research Center
> Texas Biomedical Research Institute
> P.O. Box 760549
> San Antonio, TX 78245-0549
> Telephone: (210)258-9476
> e-mail: msharp at TxBiomed.org
>
>
>
>
>> On Sep 21, 2015, at 9:52 AM, Nico Gutierrez <nico.gutierrezo at gmail.com> wrote:
>>
>> Hi All,
>>
>> I need to do the following operation from data.frame:
>>
>> df <- data.frame(Year = c("2001", "2002", "2003", "2004", "2005", "2006",
>> "2007"), Amount = c(150, 120, 175, 160, 120, 105, 135))
>> df[which.max(df$Amount),]  #to extract row with max Amount.
>>
>> Now I need to do 3 years average around the max Amount value (ie:
>> mean(120,175,160))
>>
>> Thanks!
>> N
>>
>>       [[alternative HTML version deleted]]
>>
>> ______________________________________________
>> R-help at r-project.org mailing list -- To UNSUBSCRIBE and more, see
>> https://stat.ethz.ch/mailman/listinfo/r-help
>> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
>> and provide commented, minimal, self-contained, reproducible code.
>
> ______________________________________________
> R-help at r-project.org mailing list -- To UNSUBSCRIBE and more, see
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.



More information about the R-help mailing list