0

I have a dataframe in the form of:

df:

RepName, Discount
Bob,Smith , 5383.24
Johh,Doe ,  30349.21
...

The names are repeated. In the df, RepName is a factor and Discount is numeric. I want to calculate the mean per RepName. I can't seem to get the aggregate statement right.

I've tried:

#This doesn't work
repAggDiscount <- aggregate(repdf,  by = repdf$RepName, FUN = mean)

#Not what I want:
repAggDiscount <- aggregate(repdf,  by = list(repdf$RepName), FUN = mean)

I've also tried the following:

repnames <- lapply(repdf$RepName, toString)
repAggDiscount <- aggregate(repdf,  by = repnames, FUN = mean)

But that gives me a length mismatch...

I've read the help but an example of how this should work for my data would go a long way... thanks!

7
  • Are you open to other packages? Commented Jun 12, 2014 at 18:41
  • 2
    aggregate(Discount ~ RepName, repdf, mean) perhaps? Commented Jun 12, 2014 at 18:41
  • @AnandaMahto, that seemed to work. Why did my way not work? Commented Jun 12, 2014 at 18:44
  • For big data sets use data.table package. i.e., library(data.table); setDT(repdf)[, list(Discount = mean(Discount)), by = RepName] Commented Jun 12, 2014 at 18:46
  • Because the syntax isn't quite right. You're aggregating the whole data frame and not just the relevant columns the way you've written things. Commented Jun 12, 2014 at 18:47

1 Answer 1

1

I'm posting @AnandaMahto's answer here to close out the question. You can use the formula syntax

aggregate(Discount ~ RepName, repdf, mean)

Or you can use the by= syntax

repAggDiscount <- aggregate(repdf$Discount, by = list(repdf$RepName), FUN = mean)

The problem with your syntax was that you were trying to aggregate the whole data.frame which included the RepName column where taking the mean doesn't make sense

You could also to

repAggDiscount <- aggregate(repdf[,-1], by = repdf[,1,drop=F], FUN = mean)

which is closer to the matrix style syntax.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.