[R] Extract from data.frame

John McKown john.archie.mckown at gmail.com
Mon Sep 21 19:58:07 CEST 2015


On Mon, 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
>
>
​The simplistic answer is something like:

df <- structure(list(Year = structure(1:7, .Label = c("2001", "2002",
"2003", "2004", "2005", "2006", "2007"), class = "factor"), Amount = c(150,
120, 175, 160, 120, 105, 135)), .Names = c("Year", "Amount"), row.names =
c(NA,
-7L), class = "data.frame");
wdf <- which.max(df$Amount);
adf3 <- mean(df$Amount[adf-1:adr+1]);

But that ignores the boundry condition where the maximum is at either end.
What do you want to do in that case?​


-- 

Schrodinger's backup: The condition of any backup is unknown until a
restore is attempted.

Yoda of Borg, we are. Futile, resistance is, yes. Assimilated, you will be.

He's about as useful as a wax frying pan.

10 to the 12th power microphones = 1 Megaphone

Maranatha! <><
John McKown

	[[alternative HTML version deleted]]



More information about the R-help mailing list