library(dplyr)library(tidyr)library(purrr)# df with all sows with greater than 50 hours recording before farrowingsows_to_keep <- df_wide_10 %>%group_by(sow) %>%filter(any(ttf <-50)) %>%ungroup()# Nests data by sownesteddf <- sows_to_keep %>%nest(full =-sow)# creates a new nested column for the baseline for each sow for -120 to -50nesteddf <- nesteddf %>%mutate(baseline =map( full,~ .x %>%filter(between(ttf, -120, -50)) ) )# creates another column just for the model for the iso tree and applies the model to the data for each sow to have a trained model for each sow individuallynesteddf <- nesteddf %>%mutate(iso_model =map( baseline,~isolation.forest(data = .x %>%select(-ttf), ntrees =500) ) )hour_cutoffs <-seq(-119, 120, by =1)nesteddf <- nesteddf %>%mutate(hourly_results =map2( full, iso_model,~ { full_data <- .x # calls the data model <- .y # calls the modelmap_dfr(hour_cutoffs, function(cutoff) { projected <- full_data %>%filter(ttf >=-120, ttf <=120)if (nrow(projected) ==0) return(tibble())# Predict anomaly scores scores <-predict(model, newdata = projected %>%select(-ttf)) projected <- projected %>%mutate(anomaly_score = scores)# Only fit loess if there are enough pointsif (nrow(projected) >=5) { # loess needs at least ~5 points for span=0.75 loess_mod <-loess(anomaly_score ~ ttf, data = projected, span =0.75) loess_fit <-predict(loess_mod, newdata = projected) } else { loess_fit <-NA_real_# fallback } projected %>%mutate(loess_fit = loess_fit,cutoff_hour = cutoff ) }) } ) )# Loop through each sowfor (i inseq_len(nrow(nesteddf))) { sow_id <- nesteddf$sow[i] df_plot <- nesteddf$hourly_results[[i]]# Skip if the hourly_results is emptyif (nrow(df_plot) ==0) next p <-ggplot(df_plot, aes(x = ttf,y=loess_fit)) +geom_smooth()+# geom_point(aes(y = anomaly_score), color = "blue", alpha = 0.5) +# geom_line(aes(y = loess_fit), color = "red", size = 1) +labs(title =paste("Sow", sow_id),x ="TTF",y ="Anomaly Score / Loess Fit" ) +theme_minimal(base_size =14)print(p)}
`geom_smooth()` using method = 'gam' and formula = 'y ~ s(x, bs = "cs")'
`geom_smooth()` using method = 'gam' and formula = 'y ~ s(x, bs = "cs")'
`geom_smooth()` using method = 'gam' and formula = 'y ~ s(x, bs = "cs")'
`geom_smooth()` using method = 'gam' and formula = 'y ~ s(x, bs = "cs")'
`geom_smooth()` using method = 'gam' and formula = 'y ~ s(x, bs = "cs")'
`geom_smooth()` using method = 'gam' and formula = 'y ~ s(x, bs = "cs")'
`geom_smooth()` using method = 'gam' and formula = 'y ~ s(x, bs = "cs")'
`geom_smooth()` using method = 'gam' and formula = 'y ~ s(x, bs = "cs")'
`geom_smooth()` using method = 'gam' and formula = 'y ~ s(x, bs = "cs")'