Hunk Lee
Hunk Lee

Reputation: 11

Aggregate function with ifelse

I want to get the earliest day in the data set for every MemberID. But i need to do a ifelse in the aggregate function to sort out some data. Because there are lots of transaction record but i only need the earliest one after the user adopt to mobile channel (Mobile=="1").

aggregate(Mobile$OrderDate, by=list(MemberID=Mobile$MemberID),min)

aggregate(OrderDate ~ MemberID, data=Mobile, function(x) if(Mobile=="1") 

min(OrderDate) else NA )  

Should be a list like this:

MEMBERID   Date
212        2009/04/20
....

Upvotes: 1

Views: 120

Answers (1)

Santiago Capobianco
Santiago Capobianco

Reputation: 886

You can use the subset argument in the aggregate function to select some part of your dataframe. But, you will need to use a formula interface. Here is an example with iris:

> head(iris)
  Sepal.Length Sepal.Width Petal.Length Petal.Width Species
1          5.1         3.5          1.4         0.2  setosa
2          4.9         3.0          1.4         0.2  setosa
3          4.7         3.2          1.3         0.2  setosa
4          4.6         3.1          1.5         0.2  setosa
5          5.0         3.6          1.4         0.2  setosa
6          5.4         3.9          1.7         0.4  setosa
> aggregate(Sepal.Length ~ Species, iris, subset = iris$Species %in% c("versicolor", "virginica"), min)
     Species Sepal.Length
1 versicolor          4.9
2  virginica          4.9

You havent post a dput() of your data, but I think it will be something like this:

> aggregate(OrderDate ~ MemberID, Mobile, subset = (Mobile == "1"), min)

Hope it serves you.

Upvotes: 1

Related Questions