how to calculate standard deviation of values in 10 intervals?

124 views Asked by At

I want to calculate a standard deviation step by 10 in R; for example

For a large number of values, I want to calculate the SD of the values in 10 intervals. 0-10, 10-20, 20-30 ...

Example: I have a vector of :

exemple <- seq (0,100,10)

If I do sd (example) : I have the value of standard deviation but for all values in example.

But, how can I do to calculate the standard deviation to this example selecting 10 by 10 steps ?

But instead of calculating the standard deviation of all these values, I want to calculate it between 0 and 10, between 10 and 20, between 20 and 30 etc…

I precise in interval 0-10 : we have values, in intervals 10-20, we have also values.. etc.

exemple2 0 to 10, we have values : 0.2, 0.3, 0.5, 0.7, 0.6, 0.7, 0.03, 0.09, 0.1, 0.05

An image for more illustrations : Image

Can someone help me please ?

2

There are 2 answers

1
Ronak Shah On BEST ANSWER

You may use cut/findInterval to divide the data into groups and take sd of each group.

set.seed(123)
vec <- runif(100, max = 100)
tapply(vec, cut(vec, seq(0,100,10)), sd)

#  (0,10]  (10,20]  (20,30]  (30,40]  (40,50]  (50,60]  (60,70]  (70,80]  (80,90] (90,100] 
#3.438162 2.653866 2.876299 2.593230 2.353325 2.755474 2.454519 3.282779 3.658064 3.021508 
1
Claudio On

Here is a solution using dplyr:

library(dplyr)
## Create a random a dataframe with a random variable with 1000 values between 1 and 100

df <- data.frame(x = runif(1000, 1, 100)

## Create a grouping variables, binning by 10

df$group <- findInterval(df$x, seq(10, 100, by=10))

## Calculate SD by group

df %>%
  group_by(group) %>%
  summarise(Std.dev = sd(x))

# A tibble: 10 x 2
   group St.dev
 * <int>  <dbl>
 1     0   2.58
 2     1   2.88
 3     2   2.90
 4     3   2.71
 5     4   2.84
 6     5   2.90
 7     6   2.88
 8     7   2.68
 9     8   2.98
10     9   2.89