[R] Matrix operation
arun
smartpink111 at yahoo.com
Tue Sep 24 16:34:42 CEST 2013
Hi,
Try:
set.seed(49)
qcd<- matrix(sample(1:20,124*69,replace=TRUE),ncol=69)
set.seed(345)
listt<- matrix(sample(1:80,124*5,replace=TRUE),ncol=5)
lst1<-list(c(15,2),c(56,54),c(15,62),c(4,14))
names(lst1)<- 2:5
S<- do.call(cbind,lapply(names(lst1),function(i) {ww<-listt[,as.numeric(i),drop=FALSE];indx<-lst1[[i]]; YY<- cbind(qcd[,indx[1]],qcd[,indx[2]]);M<- lm(ww~qcd[,indx[1]]+qcd[,indx[2]]); A1<- M$coef[2]; B1<- M$coef[3]; unlist(lapply(seq_len(nrow(YY)),function(i){Y<- YY[i,];A<- A1*Y[1]; B<- B1*Y[2]; Alp<- A+B} ),use.names=FALSE) }))
colnames(S)<- paste0("Alp",1:4)
dim(S)
#[1] 124 4
#or just
S1<-do.call(cbind,lapply(names(lst1),function(i) {ww<-listt[,as.numeric(i),drop=FALSE];indx<-lst1[[i]]; YY<- cbind(qcd[,indx[1]],qcd[,indx[2]]);M<- lm(ww~qcd[,indx[1]]+qcd[,indx[2]]); A1<- M$coef[2]; B1<- M$coef[3]; A<- A1* YY[,1]; B<- B1*YY[,2] ; A+B}))
colnames(S1)<- colnames(S)
identical(S1,S)
#[1] TRUE
A.K.
________________________________
From: eliza botto <eliza_botto at hotmail.com>
To: "smartpink111 at yahoo.com" <smartpink111 at yahoo.com>
Sent: Tuesday, September 24, 2013 8:04 AM
Subject:
Dear Arun,
I have the following codes to perform a certain operation
where "listt" is a matrix of dimension 124 ROW and 5 COLUMN. "qcd" has 124 rows and 69 columns. YY has 12 rows and 2 columns.
What i want to do is to make a loop so that R automatically replaces "15" in Y<-YY[15,] with the numbers from 1 to 124, every where.
So "Alp1","Alp2","Alp3" and "Alp4" should each be of 124 rows and 1 column. similarly "S",in the end,should be of dimension 124*4.
How can i do that?
I hope i am clear but if there is anything that is needed to be cleared about question please do let me know.
ww<-matrix(listt[,2],ncol=1)
YY<-cbind(qcd[,15],qcd[,2])
Y<-YY[15,]
M<-lm(ww~qcd[,15]+qcd[,2])
A<-M$coefficients[2]*Y[1]
B<-M$coefficients[3]*Y[2]
Alp1<-A+B
Alp1
ww<-matrix(listt[,3],ncol=1)
YY<-cbind(qcd[,56],qcd[,54])
Y<-YY[15,]
M<-lm(ww~qcd[,56]+qcd[,54])
A<-M$coefficients[2]*Y[1]
B<-M$coefficients[3]*Y[2]
Alp2<-A+B
Alp2
ww<-matrix(listt[,4],ncol=1)
YY<-cbind(qcd[,15],qcd[,62])
Y<-YY[15,]
M<-lm(ww~qcd[,7]+qcd[,62])
A<-M$coefficients[2]*Y[1]
B<-M$coefficients[3]*Y[2]
Alp3<-A+B
Alp3
ww<-matrix(listt[,5],ncol=1)
YY<-cbind(qcd[,4],qcd[,14])
Y<-YY[15,]
M<-lm(ww~qcd[,4]+qcd[,14])
A<-M$coefficients[2]*Y[1]
B<-M$coefficients[3]*Y[2]
Alp4<-A+B
Alp4
S<-cbind(Alp1,Alp2,Alp3,Alp4)
Thanks indeed in advance
Eliza
More information about the R-help
mailing list