Home > Blockchain >  The custom handy mean function doesn't work correctly
The custom handy mean function doesn't work correctly

Time:01-06

The function I defined returns a different result than the R function.

n <- 100
set.seed(42)  ## for sake of reproducibility
x <- rnorm(n)

mean(x > 0)
# [1] 0.54


aver <- function(x, n) {
  h <- 0
  j <- 0
  for (i in x) {
    if (i > 0) {
      h <- h   i
      j <- j   1
    }
  }
  return(h/j)
}

aver(x, 0)
# [1] 0.7949533

What is the problem?

CodePudding user response:

You have to use mean(x[x > 0]) to subset x and then you will get the same answer. x > 0 on the other hand gives a boolean vector, i.e. you attempted to calculate the mean of this boolean (which is a value between 0 and 1).

CodePudding user response:

aver <- function(x, n) {
  h <- 0
  j <- length(x)
  for (i in x) {
    if (i > n) h <- h   1 # We add 1 to h. h contains the number of x > n
  }
  return(h/j)
}

aver(x, 0)
#> 0.54
  •  Tags:  
  • Related