0

Anyone have any idea why this code is only iterating through once. The main problem I am getting is that in line 141, the filter to DeviceID == user, Time == day is doing absolutely nothing. When I check in the environment, these values of user and day seem right (see attached screenshots of environment), but the data frame final_locations_ID is not filtered to DeviceID == user, Time == day, but also isn't unfiltered (values are missing that don't really make sense). This is my first time using for loop in r, is using <- still appropriate or is this causing my issues. The next for loop, which aims to find each distinct cluster, and record the mean lat and lon points, but num only has the value of 1, which means only 1 cluster is being detected which doesn't make a ton of sense.

The goal of the code is to iterate through each user in users, then iterate through each day for each user. Run dbscan for that particular user on that day, then finding each distinctive cluster, append the mean lat and lon coordinates of each cluster for that user on that day to a list.

cluster_info <- c("hi", "hello")


for(user in users){
  for(day in days_distinct){
    final_locations_ID <- final_locations %>% filter(DeviceID == user, Time == day)
    trajectory_cluster <- dbscan(select(final_locations_ID, lat, lon), eps = .01, minPts = 8)
    final_locations_cluster <- final_locations_ID %>% mutate(Cluster = trajectory_cluster$cluster)
    numbers <- distinct(final_locations_cluster, Cluster) %>% filter(Cluster != "0")
    
    for(num in numbers){
      final_cluster_num <- final_locations_cluster %>% filter(Cluster == num)
      cluster_info <- c(cluster_info, paste("(", mean(final_cluster_num$lat), ",", mean(final_cluster_num$lon), ")"))
      
    }
  }   
}

cluster_info
  • 2
    Please provide a [mcve]. See [How to make a great R reproducible example?](https://stackoverflow.com/q/5963269/4996248) for what this would mean in R. – John Coleman Jul 22 '21 at 13:03
  • Your `for` loops are counting something, think `length(users)` or `length(days_distinct)`, and they are keeping their count in `user` and `day` respectively. But your 'answers`, `final_location_ID` for example, are not counting or cannot allocate greater than 1, or you'd be using the notation `final_location_ID[user] <- final_locations %>%`, and this would assume that prior to your for loop you've set a vector `final_location_ID <- vector(mode='whatever your return data is', length=length(users)` & etc. HTH thinking about the pitch and catch of for loops. – Chris Jul 22 '21 at 15:35

0 Answers0