removing noises with equal depth binning in R by replacing each bins with its mean or median

For example I have a vector like this :

a <- c(4, 8, 9, 15, 21, 21, 24, 25, 26, 28, 29, 34) 

and I want to do this:

Step 1:

Partition into equal-frequency (equi-depth)

Bins:

  • Bin 1: 4, 8, 9, 15

  • Bin 2: 21, 21, 24, 25

  • Bin 3: 26, 28, 29, 34

Step2:

Smoothing by bin means:

  • Bin 1: 9, 9, 9, 9

  • Bin 2: 23, 23, 23, 23

  • Bin 3: 29, 29, 29, 29

Output :

9,9,9,9,23,23,23,23,29,29,29,29 
4

2 Answers

We can create groups by dividing length of a in equal number of bins and use ave to calculate rounded mean in each group.

no_of_bins <- 4 round(ave(a, rep(1:length(a), each = no_of_bins, length.out = length(a)))) #[1] 9 9 9 9 23 23 23 23 29 29 29 29 

PS -

  • ave has default function as mean so it has not been explicitly applied.

Try this (take Orange$age predefined R variable as your input, 10 is the bin size)

v=split(Orange$age, ceiling(seq_along(Orange$age)/10)) lapply(v, function(item){rep(mean(item), length(item))}) 

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like