Error in aggregate.data.frame: no rows to aggregate

Hi all,

I am seeing this error: Error in aggregate.data.frame: no rows to aggregate when I try to aggregate a variable

aggregatevalue <- aggregate(col1 ~ col2, df, sum, na.rm = TRUE)

The error is actually true because in the df I do not have values for col1 and col2 either for the selection I am making from the app. Since, this aggregate is a part of shiny app and I would not like my app to run into error/crash rather I would like it to keep running.

How do I handle this error? So that my app does not crash?

One approach could be to add a check before you use aggregate(). First, filter df to only those cases where values exist for col1 and col2. If the result has at least one row, proceed. It could look something like below.

library(dplyr)

check = df %>%
  filter(!is.na(col1) & !is.na(col2))

if(nrow(check) > 0){
  aggregatevalue <- aggregate(col1 ~ col2, df, sum, na.rm = TRUE)
}
1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.