Skip to content
Prev 319642 / 398506 Next

Help finding first value in a BY group

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,