How to avoid “operations are possible only for numeric, logical or complex types” when computing top 3 elements in each group

The specific error is caused by you using & to separate lines of code; this does not work because that is a logical operator in R. You could use ; instead or newline characters to separate lines.

However, taking a step back you are trying to compute the top 3 months of the year for each year in your dataset, as measured by the AOD field. Since you’re using dplyr, this can be done more smoothly with something like:

AOD_median %>%
  arrange(-AOD) %>%
  group_by(year) %>%
  top_n(3, AOD) %>%
  select(year, month)
# A tibble: 6 x 2
# Groups:   year [2]
#    year month
#   <dbl> <dbl>
# 1  2000     4
# 2  2000     7
# 3  2000     5
# 4  2001     7
# 5  2001     5
# 6  2001     2

If you don’t mind the three months being out of order (by AOD), you could drop the arrange(-AOD) line.

Data:

AOD_median <- structure(list(date = c("1-Mar-00", "1-Apr-00", "1-May-00", "1-Jun-00", 

Leave a Comment

tech