rdate-sorting

Delete values from a sorted vector


I have a vector of 100 sorted values

x=rnorm(100)
x_sort=sort(x)

How can I delete 2.5% (for example) from upper un lower side of x_sort?


Solution

  • Here's one option:

    m <- 5 # percentage to be deleted from each side
    l <- length(x_sort)
    n <- l * m/100
    y <- head(tail(x_sort, l - n), l - n*2)
    
    length(x_sort)
    #[1] 100
    length(y)
    #[1] 90
    

    You could round the value of n to integers or use floor or ceiling functions, e.g. n <- round(l * m/100) to ensure that you're not trying to remove for example 2.3 elements of x.

    Another approach:

    m <- 5 # percentage to be deleted from each side
    l <- length(x_sort)
    n <- round(l * m/100)
    y2 <- x_sort[seq.int(n+1L, l-n, 1L)]
    

    Do they return the same?

    all.equal(y, y2)
    #[1] TRUE