Skip to content
Prev 383308 / 398502 Next

calculate row median of every three columns for a dataframe

Hi Anna,
I can't think of a simple way, but this function may make you happier:

step_median<-function(x,window) {
 x<-unlist(x)
 stop<-length(x)-window+1
 xout<-NA
 nindx<-1
 for(i in seq(1,stop,by=window)) {
  xout[nindx]<-do.call("median",list(x[i:(i+window-1)]))
  nindx<-nindx+1
 }
 return(xout)
}
apply(df,1,step_median,3)

This should return a matrix where the columns are the medians
calculated from blocks of "window" width on each row of "df". As Bert
noted, you may want to think about a "rolling" median where the
"windows" overlap. This can be done like so:

library(zoo)
apply(df,1,rollmedian,3)

Jim

On Fri, Apr 17, 2020 at 12:32 AM aiguo li via R-help
<r-help at r-project.org> wrote: