Helps plot the graph when the variable has equal values

The code below generates a graph with dots and a "prediction" line, so to speak. In this case, it is generating for dmda=01/07. However, I cannot generate a graph for the day 02/07 or 03/07. From what I understand it is due to the values ​​of the variable datas being equal. For example, the variable datas for 01/07 is: 12, 12, 16 and 18 - in this case it generates the graph. For 02/07 it is 13, 13, 13 and for 03/07 is 11 and 11. Because these values ​​are equal, the nls function does not work. So what I would like to do is:

When the values ​​of the variable datas are equal, the code would not need to go through the nls function, but would generate the graph with the red dot being the value obtained by the variable datas, that is, if it is for 03/07, the graph would have the line of "predction" going to 11 same. I put an image to illustrate.

I appreciate any help!

library(dplyr)
library(lubridate)
library(tidyverse)

df1 <- structure(
  list(date1 = c("2021-06-28","2021-06-28","2021-06-28","2021-06-28","2021-06-28",
                 "2021-06-28","2021-06-28","2021-06-28"),
       date2 = c("2021-04-02","2021-04-03","2021-04-08","2021-04-09","2021-04-10","2021-07-01","2021-07-02","2021-07-03"),
       Week= c("Friday","Saturday","Thursday","Friday","Saturday","Thursday","Friday","Monday"),
       DR01 = c(14,11,14,13,13,14,0,0), DR02= c(14,12,16,17,13,12,0,0),DR03= c(19,15,14,13,13,12,0,0),
       DR04 = c(15,14,13,13,16,12,13,0),DR05 = c(15,14,15,13,16,12,13,11),
       DR06 = c(21,14,13,13,15,16,13,11),DR07 = c(12,15,14,14,19,14,13,11)),
  class = "data.frame", row.names = c(NA, -8L))

dmda<-"2021-07-01"

datas<-df1 %>%
  filter(date2 == ymd(dmda)) %>%
  summarize(across(starts_with("DR"), sum)) %>%
  pivot_longer(everything(), names_pattern = "DR(.+)", values_to = "val") %>%
  mutate(name = as.numeric(name))
colnames(datas)<-c("Days","Numbers")

dif <- as.Date(dmda) - as.Date(df1$date1[1]) + 1
datas <- datas[dif:max(datas$Days, na.rm = TRUE),]

plot(Numbers ~ Days, xlim=c(0,8), ylim=c(0,20), data = datas,xaxs='i')
mod <- nls(Numbers ~ b1*Days^2+b2,start = list(b1 = 0,b2 = 0), data = datas)
new.data <- data.frame(Days = with(datas, seq(min(Days),max(Days),len = 45)))
new.data <- rbind(0, new.data)
lines(new.data$Days, predict(mod, newdata=new.data))
points(0, coef(mod)[2], col="red", pch=19, cex=1.2, xpd=TRUE)

enter image description here

Example for 03/07
enter image description here

if you specify the algorithm 'port', you would seem to get the visual output you would expect without further changes.

mod <- nls(Numbers ~ b1*Days^2+b2,start = list(b1 = 0,b2 = 0), data = datas,algorithm = "port")

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.