# [R] loop for column substraction of a matrix

Sat Oct 6 00:26:42 CEST 2012

```Or, using your mapply solution, compute

rs <- rowSums(mat1)

and then use it for all subtractions. With a larger dataset this would
be probably faster.

Em 05-10-2012 22:41, arun escreveu:
> Hi,
>
> Sorry, I think I misunderstand your question (after reading Rui's solution).
>
> You can also try any of these to get the result if this is what you meant:
> set.seed(1)
> mat1<-matrix(sample(1:500,380,replace=TRUE),ncol=38)
> res1<-t(do.call(rbind,lapply(1:ncol(mat1), function(i) mat1[,i]-apply(mat1,1,sum))))
> #or
> res1<-sapply(1:ncol(mat1), function(i) mat1[,i]-apply(mat1,1,sum))
> #or
> res1<-mapply(FUN=function(i) mat1[,i]-rowSums(mat1), 1:ncol(mat1))
> 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: Friday, October 5, 2012 4:05 PM
> Subject: [R] loop for column substraction of a matrix
>
>
> Dear useRs,
>
>
> I have a matrix with 38 columns and 365 rows. what i want to do is the following.....
>
> 1. subtracting from each column, first itself and then all the remaining columns. More precisely, from column number 1, i will first subtract itself(column 1) and then the remaining 37 columns. Afterwards i will take column number 2 and do the same. In this way i want to proceed till 38th column.
> 2. i want to print the resulting matrix on A4 paper.
>
> Bundle of thanks in advance.
>
> best regards
> eliza
>
>
>
>      [[alternative HTML version deleted]]
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help