0

I have a for loop that creates a series of maps for each of the unique crimes types in a list. These maps are then exported to a powerpoint presentation pres_1.

for(i in unique(crime_df$crime_type)) {
  crime_map <- ggplot(data = filter(crime_df, crime_type== i)) + 
    geom_sf(aes(geometry = geometry, fill = curr_yr_count))
pres_1 <- add_slide(pres_1, layout = "Title and Content", master = "Office Theme")
pres_1 <- ph_with(pres_1, value = crime_map, location = ph_location_type(type = "body"))
}

I would like to move the map slides to elsewhere within the presentation, based on the iteration number of the loop - e.g. the first map produced should go to slide 20, the second to slide 22 etc. However, the value of i refers to the value of crime_type, which is non-numeric (e.g. robbery etc.).

Is there any way to get the numeric value of i so I could add the following line of code to the end of the loop? pres_1 <- move_slide(pres_1, index = length(pres_1), to = 22 + i)

Ant
  • 313
  • 5
  • 19
  • 2
    The way you've defined your loop `i` doesn't have a numeric value. *"Is there any way to get the numeric value of `i`*"--there is no "numeric value of `i`" to get. You can define a separate `counter` that starts at 1 and increments at the end of each loop, or you can rewrite your loop so `i` is numeric. Or maybe just define `slide <- 20` before the loop and put `slide <- slide + 2` as the last line inside the loop, since it's that sequence you want. – Gregor Thomas Sep 20 '22 at 16:00
  • @GregorThomas defining `slide <- 20` and then increasing this by `2` each time the loop iterated worked - it helped not to think of `i` as not inherently numeric. – Ant Sep 21 '22 at 07:48
  • 1
    Glad to hear it helped. Yes, R's loops are very flexible, which can make them confusing. I almost always set up my loops so that my iterator is numeric. If you're not consistent, the you should make a habit of consciously deciding whenever you write a loop to use a numeric or non-numeric iterator. Numerics are often easier, especially if you need to use the iterator on multiple objects (e.g., column values and column names, or in your case data values and slide numbers). – Gregor Thomas Sep 21 '22 at 15:04

0 Answers0