Function to calculate a limit value

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:
image
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?

For the future, please when you share your code, share it as out of your script, when you run it and paste from your console, you are sending new line characters of > on every row, which forum users have to remove... I have edited your post to be clean in this respect.

I fixed your function in a few important ways that I think will serve you well. Avoid modifying objects with global assignment wherever possible <<- ; It's a recipe for confusion, and is not often warranted. In a similar vein, always be suspicious when you create a function that takes parameters and those parameters aren't used in the function code body.

Your main issue seemed to be the assignment you wanted to do was to a particular position, the 'i-th' position of limit, and not to limit generally ('all the values')

y <- data.frame(
           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)
)
controll <- function(database){
    database$limit <- 0
  for (i in 11:nrow(y)) {
    database$limit[i] <- sum(mean(database[11:i,1]) ,
                       3* sd(database[11:i,1]),na.rm=TRUE) # sd() of a single value is NA 
  }
    database
}

(y2 <- controll(y))

This topic was automatically closed 7 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.