0

I'm trying to loop through a piece of code 25 times. Each time I want the loop iteration to feed into the filter (e.g., on the 16th run, the filter will equal 16) and then ouput the results into a new object for each run. Here's how you could do it manually, without using a for loop:

output1 <- df %>%
  filter(cluster == 1) %>%
  distinct() %>%
  st_as_sf(coords = c("mx","my"), crs = 4326)
output2 <- df %>%
  filter(cluster == 2) %>%
  distinct() %>%
  st_as_sf(coords = c("mx","my"), crs = 4326)
output3 <- df %>%
  filter(cluster == 3) %>%
  distinct() %>%
  st_as_sf(coords = c("mx","my"), crs = 4326)
output4 <- df %>%
  filter(cluster == 4) %>%
  distinct() %>%
  st_as_sf(coords = c("mx","my"), crs = 4326)

I know I'm going to need to do this in other areas too, so the manual way obviously isn't ideal. I'm trying to construct a for loop that will do it for me:

for (i in 1:25) {
  output[i] <- df %>%
    filter(cluster == i) %>%
    distinct() %>%
    st_as_sf(coords = c("mx","my"), crs = 4326)
}

When I run it I get "Error: object 'output' not found". Can anyone tell me what I'm doing wrong?

Thanks!

Obed
  • 403
  • 3
  • 12

0 Answers0