[R] loop command to matrix

arun smartpink111 at yahoo.com
Wed Nov 28 03:11:29 CET 2012


HI Eliza,
No problem.
You could also use:

set.seed(5)
mat1<-matrix(sample(1:400,80,replace=TRUE),ncol=8,nrow=10)
library(plyr)

resnew<-do.call(cbind,lapply(alply(mat1,2),function(x) x-colMeans(t(mat1)[!colnames(mat1)%in%names(alply(mat1,2))[match.call()[[2]][[3]]],])))


resprev<-t(do.call(rbind,lapply(lapply(split(mat1,col(mat1)),function(x) cbind(matrix(x,ncol=1),mat1)),function(x){ res1<-rowMeans(t(apply(x,1,function(x) x[!(duplicated(x)|duplicated(x,fromLast=TRUE))])))
  res<-x[,1]-res1
  res})))
 identical(resprev,resnew)
#[1] TRUE
A.K.


________________________________
From: eliza botto <eliza_botto at hotmail.com>
To: "smartpink111 at yahoo.com" <smartpink111 at yahoo.com> 
Sent: Tuesday, November 27, 2012 1:53 PM
Subject: RE: [R] loop command to matrix



thanks arun. i m more interested in learning commands. 
thankyou so much
eliza


> Date: Tue, 27 Nov 2012 10:45:37 -0800
> From: smartpink111 at yahoo.com
> Subject: Re: [R] loop command to matrix
> To: eliza_botto at hotmail.com
> CC: ruipbarradas at sapo.pt
> 
> HI Eliza,
> 
> I just saw Rui's solution.  It is much simpler than mine.
> A.K.
> 
> 
> 
> ----- Original Message -----
> From: eliza botto <eliza_botto at hotmail.com>
> To: "r-help at r-project.org" <r-help at r-project.org>
> Cc: 
> Sent: Tuesday, November 27, 2012 12:51 PM
> Subject: [R] loop command to matrix
> 
> 
> Dear UseRs,Extremely sorry for a basic question. I have a matrix of 19 rows and 365 columns. what i want to do is the following...First i want to leave out column number 1 and want to calculate the row wise mean of the remaining columns, which will obviously give me 365 values in one column, and then subtracting these values from the column i left out i.e. col=1 then i want to leave out column 2 and calculate the row wise mean of the remaining columns which includes column 1 too and then subtracting these values from the column i left out i.e. col=2.and then continuing this process the last column. i know a kind of "manual way" of doing things but its extremely long and laborious.Is there any loop command or shorter way??
> thanks in advanceregardseliza                            
>     [[alternative HTML version deleted]]
> 
> ______________________________________________
> R-help at r-project.org mailing list
> 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.
>




More information about the R-help mailing list