Home > Back-end >  How to find elements of vector which correspond to range?
How to find elements of vector which correspond to range?

Time:11-21

I have a problem with my code in R. I just began to study this program. I have to count the average value for the numbers in the vector that fit within the range between the maximum and minimum. I wrote a code and the result is not correct, I have the impression the range doesn't work.

x.sd <- function(x) {
  x.sd <- sqrt(var(x))
}
x.min <- function (x) {
  x.min <- x.m(x) - 2 * x.sd(x)
}
x.max <- function(x){
  x.max <- x.m(x)   2 * x.sd(x)
}
res <- 0
i <- res   1
for (i in 1:length(x)) {
  x_i <- function(x){
  x_i <- c(c(x.min(x) <= x) & c(x <= x.max(x)))
  i_x <- which(x_i == TRUE)
  }
  x_m <- function(x){
    x_m <- x[i_x] 
    return(x_m)
x.m2 <- function(x_m){
  x.m2 <- sum(x_m)/length(x_m)

Could you please help me to fix this problem or give me some advice on which function I can use?

CodePudding user response:

Maybe this works for you, although I might miss some parts of your code.

min_x <- function(x) x - 2 * sd(x)
max_x <- function(x) x   2 * sd(x)

mean(c(max_x(my_vec)[my_vec < mean(max_x(my_vec))], 
       min_x(my_vec)[my_vec > mean(min_x(my_vec))]))
[1] 42.67784

CodePudding user response:

I'm having a hard time following your code, but are you looking for something like this?

x <- c(10, 52, 52, 41, 35, 45, 42, 45, 52, 41, 52, 50, 0)
mean(x[abs(x - mean(x)) < 2*sd(x)])
#> [1] 43.08333

This matches the expected output mentioned in the comments.

  • Related