# Make condition for graph generation when there are two points

Could you help me make a condition for the code below. Before explaining what I want, I'll explain in general the purpose of the code. The code basically generates a graph with a few dots and a "prediction" line, so to speak.

If I generate the graph for `CDE`, notice that it is 4 points, and for `ABC` it is 2 points. However, I would like to make a condition that when I have two points, the "prediction" line is the `mean` and I don't use the `model` function there that I do. So for the `ABC` graph the line should go towards 6.4.

Could you help me adjust this?

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

dmda<-"2021-07-07"

datas <- structure(
list(Code = c("CDE","CDE","CDE","CDE","ABC","ABC"),
Days = c(39,40, 41,42,43,44),
Numbers = c(5.5,5.5,6,6.5,7,8)),
class = "data.frame", row.names = c(NA, -6L))

f1 <- function(dat, code_nm) {
dat <- subset(dat,  Code == code_nm)

plot(Numbers ~ Days,  xlim= c(0,45), ylim= c(0,30),
xaxs='i',data = dat,main = paste0(dmda, "-", code_nm))
if (var(dat\$Numbers)>0){

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

new.data <- data.frame(Days = with(dat, seq(min(Days),max(Days),len = 45)))
new.data <- rbind(0, new.data)
lines(new.data\$Days,predict(model,newdata = new.data),lwd=2)
coef<-coef(model)
points(0, coef, col="red",pch=19,cex = 2,xpd=TRUE)
text(.99,coef + 1,max(0, round(coef,1)), cex=1.1,pos=4,offset =1,col="black")} else {
yz <- unique(dat\$Numbers)
lines(c(0,dat\$Days), c(yz, dat\$Numbers), lwd = 2)
points(0, yz, col = "red", pch = 19, cex = 2, xpd = TRUE)
text(.1,yz+ .5,round(yz,1), cex=1.1,pos=4,offset =1,col="black")
}

}

f1(datas, "CDE")
``````

Use mean when it's two points.

``````m<-mean(datas\$Numbers)
> m
 6.416667
``````

For `ABC` Are you asking how to do a horizontal line at a given height ? If so the function is called abline

abline(h=mymean)

Ps.

I strongly recommend against naming results with the same name as an R function

1 Like

Thanks for the answer @nirgrahamuk ! Probably I have to use the `abline` function, but how can I this condition, for example, if it's two points or less, use `abline` function, if it's three points or more, use `nls` function?

if you want to know how many rows there are use nrow
`nrow(dat)`
you can execute conditional logic with if()/else() structures. You already use if in your code

Thanks for reply @nirgrahamuk . I will try to adjust to see if I can.

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.