Please write a function to compute the expected value and standard deviation of an array of values. Compare your results with that of R’s mean and std functions.

x <- c(4,1,3,7,8,6,5,5)

# Create a function to calculate the expected value

mean_x <- function(x){
  return(sum(x)/length(x))
}

#invoking the function
exp_value<-mean_x(x)

#compare result with R'mean
print(exp_value)
## [1] 4.875
mean(x)
## [1] 4.875
# Function to calculate standard deviation
std_x <-function(x){
 return(sqrt(sum((x-mean_x(x))^2)/(length(x)-1)))
}

#invoking the function
std_dev<-std_x(x)

#compare result with R'standard deviation
print(std_dev)
## [1] 2.232071
sd(x)
## [1] 2.232071

Now, consider that instead of being able to neatly fit the values in memory in an array,you have an infinite stream of numbers coming by. How would you estimate the mean and standard deviation of such a stream? Your function should be able to return the current estimate of the mean and standard deviation at any time it is asked. Your program should maintain these current estimates and return them back at any invocation of these functions. (Hint: You can maintain a rolling estimate of the mean and standard deviation and allow these to slowly change over time as you see more and more new values).

# The function has 2 parts, one wil calculate the cumulative mean and sd and the other part wil calculate the new stream of numbers coming by. 



x1<- c(3,5,4,4,7,9,12,3)
x2<- c(4,5,6)

moving <-function(stat = list(), vec){
  if(length(stat) !=0){
    new_len <- stat$n + length(vec)
    meannew <-(stat$n*stat$mean +sum(vec))/new_len
    sum_old<- stat$n*stat$mean
    sum_new<- sum_old + sum(vec)
    sum_squared<- stat$sum_squared + sum(vec^2)
    sd_squared <- new_len*meannew^2 - 2*meannew*sum_new + sum_squared
    sdnew <-sqrt(sd_squared/new_len)
  }else{
    new_len <-length(vec)
    meannew <-sum(vec)/new_len
    sum_new<-sum(vec)
    sum_squared<- sum(vec^2)
    sd_squared<-new_len*meannew^2 - 2*meannew*sum_new + sum_squared
    sdnew<- sqrt(sd_squared/new_len)
    
  }
  return(list(mean = meannew, sd = sdnew, n = new_len, sum_squared = sum_squared))
  }
cum <- moving(vec = x1)
moving(stat = cum, vec = x2)
## $mean
## [1] 5.636364
## 
## $sd
## [1] 2.637931
## 
## $n
## [1] 11
## 
## $sum_squared
## [1] 426