[R] multiply each row in a matrix with the help of the for loop
arun
smartpink111 at yahoo.com
Tue Nov 13 15:25:30 CET 2012
HI,
May be this helps:
list1<-lapply(lapply(1:3,function(i) {aa[1:i,,i]<-a[1:i,]*-1
return(aa[,,i])}),function(x) apply(x,2,function(i) ifelse(i==0,1,x)))
res<-array(unlist(list1),dim=c(nrow(list1[[1]]),ncol(list1[[1]]),length(list1)))
res
#, , 1
#
# [,1] [,2] [,3]
#[1,] -1 -1 -1
#[2,] 1 1 1
#[3,] 1 1 1
#, , 2
#
# [,1] [,2] [,3]
#[1,] -1 -1 -1
#[2,] -1 -1 -1
#[3,] 1 1 1
#
#, , 3
# [,1] [,2] [,3]
#[1,] -1 -1 -1
#[2,] -1 -1 -1
#[3,] -1 -1 -1
A.K.
----- Original Message -----
From: Haris Rhrlp <haris_r_help at yahoo.com>
To: "R-help at r-project.org" <R-help at r-project.org>
Cc:
Sent: Tuesday, November 13, 2012 7:41 AM
Subject: [R] multiply each row in a matrix with the help of the for loop
Dear R users,
I have this program
aa<-array(rep(0,27),dim=c(3,3,3))
a<-matrix(rep(1,9),ncol=3)
n<-0
for (i in 1:3) {
a[i,]<-a[i,]*(-1)
n<-n+1
aa[,,n]<-a[i,]
}
but i real want to multiply each row with -1 according to for loop and after that to put it in the array.
I will give an example for what excaclty want
-1 -1 -1
1 1 1
1 1 1
-1 -1 -1
-1 -1 -1
1 1 1
-1 -1 -1
-1 -1 -1
-1 -1 -1
[[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