[R] Help finding first value in a BY group

arun smartpink111 at yahoo.com
Fri Mar 15 18:37:38 CET 2013


Hi,
Try:
data.frame(Forecast=with(PeriodSKUForecast,tapply(Forecast,SKU,head,1)))
#   Forecast
#A1       99
#K2      207
#X4       63

#or
 aggregate(Forecast~SKU,data=PeriodSKUForecast,head,1)
#  SKU Forecast
#1  A1       99
#2  K2      207
#3  X4       63

#or
library(plyr)
ddply(PeriodSKUForecast,.(SKU),summarise, Forecast=head(Forecast,1))
#  SKU Forecast
#1  A1       99
#2  K2      207
#3  X4       63
A.K.




----- Original Message -----
From: Barry King <barry.king at qlx.com>
To: r-help at r-project.org
Cc: 
Sent: Friday, March 15, 2013 1:30 PM
Subject: [R] Help finding first value in a BY group

I have a large Excel file with SKU numbers (stock keeping units) and
forecasts which can be mimicked with the following:

Period <- c(1, 2, 3, 1, 2, 3, 4, 1, 2)
SKU <- c("A1","A1","A1","X4","X4","X4","X4","K2","K2")
Forecast <- c(99, 103, 128, 63, 69, 72, 75, 207, 201)
PeriodSKUForecast <- data.frame(Period, SKU, Forecast)
PeriodSKUForecast

  Period SKU Forecast
1      1  A1       99
2      2  A1      103
3      3  A1      128
4      1  X4       63
5      2  X4       69
6      3  X4       72
7      4  X4       75
8      1  K2      207
9      2  K2      201

I need to create a matrix with only the first forecast for each SKU:

A1 99
X4 63
K2 207

The Period for the first forecast will always be the minimum value
for an SKU.

Can anyone suggest how I might accomplish this?

Thank you,



-- 
__________________________
*Barry E. King, Ph.D.*
Director of Retail Operations
Qualex Consulting Services, Inc.
Barry.King at qlx.com
O: (317)940-5464
M: (317)507-0661
__________________________

    [[alternative HTML version deleted]]

______________________________________________
R-help at r-project.org mailing list
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