[R] correlation and matrix
Nathalie.Cornileau at csiro.au
Nathalie.Cornileau at csiro.au
Mon Jul 30 08:12:24 CEST 2007
Dear everyone,
I am new in R and I've got difficulties in realizing the following
tasks:
-I have variables (factors) with different numbers of levels, either 1,
2 or 3.
-I have a matrix containing these 204 factors and I have to correlate
them by groups of 4 variables.
-I have to delete the factors just having one level ( because when
correlating one-level factors, the output is NA)
here is my code:
lst<-seq(1, 204, by=12) % there are 12 factors for 17 natural resources
for (n in lst)
{
Mx<- matrix(0, byrow = F, ncol = 4, nrow=nrow(dta)) % I extract the 4
factors I have to correlate and I'd like to do it for each n
{if (nlevels(dta[,n+4])!=1)
Mx[,1]<-dta[,n+4]
else
Mx[,1]<-NA}
{if (nlevels(dta[,n+5])!=1)
Mx[,2]<-dta[,n+5]
else
Mx[,2]<-NA}
{if (nlevels(dta[,n+7])!=1)
Mx[,3]<-dta[,n+7]
else
Mx[,3]<-NA}
{if (nlevels(dta[,n+8])!=1)
Mx[,4]<-dta[,n+8]
else
Mx[,4]<-NA}
p<-0 % I compute the number of non - NA columns and I'd
like to delete the Na columns from that matrix
for (i in 1:4)
{
if(!is.na(sum(Mx[,i])>0)) p<-p+1
}
print(p)
{if (p==0 | p==1) stop("computation impossible")
else {
r<-0
for (i in 1:4)
{
if(is.na(sum(Mx[,i])>0)) r<-i
}
print(r)
print(cor((as.matrix(Mx[,-r])), use="complete.obs", method="spearman"))
}
}
} %The problem is the last step doesn't work for p==2.
In fact, it seems the loop for doesn't work either.
I hope it is clear enough and I thank you in advance for your help.
Nathalie
More information about the R-help
mailing list