Would be helpful if you provide a few sample rows and expected outcome here. There's nothing inherently wrong with the syntax that I can see, but without an understanding of what you're working with and what you're trying to achieve it's hard to be sure. That said, it is a bit unusual to see an un-aggregated aggr() function contained within an if() function - this is usually not what people are trying to achieve.