[R] for (i in...)
William Revelle
lists at revelle.net
Mon Dec 10 01:21:51 CET 2007
At 3:27 PM -0500 12/9/07, Duncan Murdoch wrote:
>On 09/12/2007 3:04 PM, Rina Oldager Miehs wrote:
>> Hey
>>
>> do anyone know why this error occurs??
>>
> >> for(i in 1:n_trait){
>> + for( j in 1:n_trait){
>> + rG[i,j] <- (G_o[i,j]/(sqrt(G_o[i,i]%*%G_o[j,j]))
>> + rP[i,j] <- (P_o[i,j]/(sqrt(P_o[i,i]%*%P_o[j,j]))
>> Error: unexpected symbol in:
> > " rG[i,j] <- (G_o[i,j]/(sqrt(G_o[i,i]%*%G_o[j,j]))
>> rP"
>
>Your parentheses don't match on the rG line. You have 3 lefts and 2 rights.
>
>Duncan Murdoch
Rina,
Alternatively, you could avoid the entire double loop by using
matrix operations. I show this and then reproduce it using the first
section of your code:
#how to use matrices to avoid looping
n_trait <- 5
X <- matrix( rnorm(100*n_trait),ncol= n_trait) #create a data matrix
G_o <- t(X) %*% X #create the G_o matrix as a matrix of cross products
G_o #show the cross products
dG <- diag(1/sqrt(diag(G_o))) #divide by the sqrt of the diagonal
rG <- dG %*% G_o %*% dG
rG #show the result
#######################
#abbreviated Rina code using loops
for(i in 1:n_trait){
for( j in 1:n_trait){
rG[i,j] <- G_o[i,j]/(sqrt(G_o[i,i]%*%G_o[j,j])) }}
rG #compare to above
Bill
--
William Revelle http://personality-project.org/revelle.html
Professor http://personality-project.org/personality.html
Department of Psychology http://www.wcas.northwestern.edu/psych/
Northwestern University http://www.northwestern.edu/
Use R for statistics: http://personality-project.org/r
More information about the R-help
mailing list