Home > Net >  Function in R to calculate a limit value
Function in R to calculate a limit value

Time:08-25

I want to set up a function that calculate a value as: mean(dataset from 11 to i) 3* standard deviation(dataset from 10 to i) where i correspond to the number of the row, like the example:

enter image description here

The first 10 value are set to 0. My actual code is:

 y <- c(1,1,1.1,1,0.9,1,1,1.1,1,0.9,1,1.1,1,1,0.9,1,1,1.1,1,1,1,1,1.1,0.9,1,1.1,1,1,0.9,
        1,1.1,1,1,1.1,1,0.8,0.9,1,1.2,0.9,1,1,1.1,1.2,1,1.5,1,3,2,5,3,2,1,1,1,0.9,1,1,3,
        2.6,4,3,3.2,2,1,1,0.8,4,4,2,2.5,1,1,1)
 y <- as.data.frame(y)
 
 controll <- function(database){
   for (i in 1:10) {
     y$limit <<- 0
   }
   for (i in 11:nrow(y)) {
     avg <- mean(y[11:i,1])
     dev <- sd(y[11:i,1])
     y$limit <<- avg   3* dev
   }
 }
 
 controll(y)

but with this function I have a single limit value for everi column. How can I solve?

CodePudding user response:

if I understood your algorithm in excel page correctly then changing controll as follows will do it:

controll <- function(database){
  for (i in 1:10) {
    y$limit <<- 0
  }
  for (i in 11:nrow(y)) {
    avg <- mean(y[1:i-1,1])
    dev <- sd(y[1:i-1,1])
    y$limit[i] <<- avg   3* dev
  }
  return(y)
}
  • Related