[R] correlation and matrix
Jacques VESLOT
Jacques.Veslot at avignon.inra.fr
Mon Jul 30 10:16:57 CEST 2007
it should be smth like that:
apply(sapply(seq(1, 204, by=12), seq, length=4), 2, function(x)
{
M <- dta[,x]
z <- sapply(M, nlevels) # if dta is a dataframe
if (sum(z==1)<3) cor(as.matrix(M[,z!=0]), use="comp", method="spear")
else NA
})
Jacques VESLOT
INRA - Biostatistique & Processus Spatiaux
Site Agroparc 84914 Avignon Cedex 9, France
Tel: +33 (0) 4 32 72 21 58
Fax: +33 (0) 4 32 72 21 84
Nathalie.Cornileau at csiro.au a écrit :
> 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
> ______________________________________________
> R-help at stat.math.ethz.ch 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