+4 votes
in Programming Languages by (5.4k points)
From a vector, I want to select all elements within two standard deviations of the vector elements. Is there any R function for such selection?

1 Answer

0 votes
by (33.7k points)

You need first to find the indices of all those elements within 2 standard deviations of the vector. Then you can use those indices to select such elements.

Here is an example:

> aa <- c(10,12,324,13,345,32,56,73,87,19,23,45,67, 20,42,120, 112)
> pos = abs(aa - mean(aa)) <= 2*sd(aa)
> pos
 [1]  TRUE  TRUE FALSE  TRUE FALSE  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE
> bb <- aa[pos]
> bb
 [1]  10  12  13  32  56  73  87  19  23  45  67  20  42 120 112
>

If you want to use one line code, you can combine two statements like this:

> bb <- aa[abs(aa - mean(aa)) <= 2*sd(aa)]
> bb
 [1]  10  12  13  32  56  73  87  19  23  45  67  20  42 120 112

...