[R] Using loop for applying function on matrix
Pascal Oettli
kridox at ymail.com
Tue May 21 10:29:05 CEST 2013
Hi,
?sweep
mdat <-
matrix(c(1,11,2,10,5,2,12,3,9,6,3,13,4,8,7,4,10,5,9,8,5,10,6,10,4),5,5)
x <- c(14,15,10,11,18)
sweep(mdat*100, 2, x, FUN='/')
[,1] [,2] [,3] [,4] [,5]
[1,] 7.142857 13.33333 30 36.36364 27.77778
[2,] 78.571429 80.00000 130 90.90909 55.55556
[3,] 14.285714 20.00000 40 45.45455 33.33333
[4,] 71.428571 60.00000 80 81.81818 55.55556
[5,] 35.714286 40.00000 70 72.72727 22.22222
Hope this helps,
Pascal
On 05/21/2013 04:16 PM, Suparna Mitra wrote:
> Hello R Experts,
> I need a bit of help in using loop.
> I have a matrix onto which I need to use several functions.
>
> In a simplified form suppose my matrix is
>> mdat
> [,1] [,2] [,3] [,4] [,5]
> [1,] 1 2 3 4 5
> [2,] 11 12 13 10 10
> [3,] 2 3 4 5 6
> [4,] 10 9 8 9 10
> [5,] 5 6 7 8 4
>
> And I have one vector
>> x
> [1] 14 15 10 11 18
>
> Now suppose in simple form I want to create a matrix in which each col
> value will be divided with consecutive no from vector x. For example
>
> column 1 of new vector will be C1=mdat[,1]*100/x[1]
>
>> C1
> [1] 7.142857 78.571429 14.285714 71.428571 35.714286
>
> Now how can I use the loop to have the complete vector at a time?
> I tried something like this, but in vain.
> for(i in 1:5) {
> Data=(mdat[,i]*100/x[i], add=T)
> }
>
> Any help will be really great.
> Thanks,
> Mitra
>
> [[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