I'm writing some code to plot a control chart in shiny(I don't have to use the qichart library) and I'm struggling to find a solution about the error "Replacement has length zero", I already know this error indicates NULL or a length 0 vector. I tried step by step to solve it in the console and the error doesn't appear and I think it's strange. I'm using for loops because I have no practice with the "apply & co" function. I'm pasting part of the code for better comprehension. I've found out that the problem is in the for a loop when I build MR, how can I solve it? Thanks in advance.
day <- input$date
type <- input$type
region <- input$region
pnc <- input$range
d2 <- 1.128
request <- filter(region_dataset, region_dataset$data>=day & region_dataset$denominazione_regione==region)
request <- request[,c(1,2,23,29,which(colnames(request)==(gsub(" ","_",input$type))))]
pbar <- mean(request[,5])
sigmapi <- as.data.frame(matrix(nrow = nrow(request),ncol = 1))
zetai <- as.data.frame(matrix(nrow = nrow(request),ncol = 1))
MR <- as.data.frame(matrix(nrow = nrow(request),ncol = 1))
UCL <- as.data.frame(matrix(nrow = nrow(request),ncol = 1))
LCL <- as.data.frame(matrix(nrow = nrow(request),ncol = 1))
CL <- as.data.frame(matrix(nrow = nrow(request),ncol = 1))
for (i in 1:nrow(request)){
if(input$type=="p positivi"){
sigmapi[i,1] <- sqrt((pnc*(1-pnc))/as.numeric(request[i,4]))
}
else if(input$type=="p nuovi positivi"){
sigmapi[i,1] <- sqrt((pnc*(1-pnc))/as.numeric(request[i,3]))
}
}
for (i in 1:nrow(request)){
zetai[i,1] <- as.numeric(request[i,5]-pnc)/sigmapi[i,1]
}
for(i in 2:nrow(request)){
MR[1,1] <- 0
MR[i,1] <- as.numeric(abs(zetai[i,1]-zetai[i-1,1]))
}
MRbar <- (sum(MR)/as.numeric((nrow(request))-1))
sigmaz <- MRbar/d2
for(i in 1:nrow(request)){
UCL[i,1] <- pbar + 3*sigmaz*sigmapi[i,1]
LCL[i,1] <- pbar - 3*sigmaz*sigmapi[i,1]
}
CL <- rep.int(pbar,times = nrow(request))
laney <- data.frame(request$data,"pnc"=request[5]) )} ```