Search code examples
rfiltermeanmedian

Median Filter in R


I have number of points and i need to convert mean filter (as mentioned below) into median filter for smoothing the plot. Can anyone please guide me in this ?

# Mean Filter
smoothfilter <- function(feat, ntap) 
{
    ofeat <- feat                             # Actual data 
    nfeat <- length(feat)                     # Length of a actual data  
    nhtap <- floor(ntap / 2.0)                                                  

    sf <- feat[1:(nfeat-ntap+1)]              
    for (j in 2:ntap) {
        sf <- sf + feat[j:(nfeat-ntap+j)]       
    }

    sf <- sf / ntap
    ofeat[(nhtap+1):(nfeat-nhtap)] <- sf
    ofeat 
}

Solution

  • Here is two function for an average filter and a median filter :

    mav <- function(x,n=5){filter(x,rep(1/n,n), sides=2)} #Average
    mmed <- function(x,n=5){runmed(x,n)} #Median