[R] calculate row median of every three columns for a dataframe

Bert Gunter bgunter@4567 @end|ng |rom gm@||@com
Fri Apr 17 03:04:35 CEST 2020


Inline.

Bert Gunter

"The trouble with having an open mind is that people keep coming along and
sticking things into it."
-- Opus (aka Berkeley Breathed in his "Bloom County" comic strip )


On Thu, Apr 16, 2020 at 5:28 PM Jim Lemon <drjimlemon using gmail.com> wrote:

> 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,

Nope. This was *not* what Bert noted. But what Bert noted may not be at all
what
Aiguo wanted anyway.

-- Bert



> 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 using r-project.org> wrote:
> >
> >  Hi all,
> > I need to calculate a row median for every three columns of a
> dataframe.  I made it work using the following script, but not happy with
> the script.  Is there a simpler way for doing this?
> > df = data.frame("a"=c(2,3,4),
> "b"=c(3,5,1),"c"=c(1,3,6),"d"=c(7,2,1),"e"=c(2,5,3),"f"=c(4,5,1))tmed <-
> function(dt) {x = apply(dt,1,median); return(x)}n =seq(1,
> ncol(df),3)w=0;for (i in n) {   m=i+2;  dt = df[,i:m];   y=tmed(dt);    w =
> cbind(w,y)}t.med <- w[,2:3]
> > Thanks,
> > Anna
> >
> >
> >         [[alternative HTML version deleted]]
> >
> > ______________________________________________
> > R-help using r-project.org mailing list -- To UNSUBSCRIBE and more, see
> > https://stat.ethz.ch/mailman/listinfo/r-help
> > PLEASE do read the posting guide
> http://www.R-project.org/posting-guide.html
> > and provide commented, minimal, self-contained, reproducible code.
>
> ______________________________________________
> R-help using r-project.org mailing list -- To UNSUBSCRIBE and more, see
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide
> http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>

	[[alternative HTML version deleted]]



More information about the R-help mailing list