[R] 3-dimensional looping Q.
Peter Wolf
s-plus at wiwi.uni-bielefeld.de
Thu Jan 8 12:00:27 CET 2004
You can compute cor by hand without loops but the code is not much
faster (dim(slp)[1]==3):
<<*>>=
set.seed(13)
n<-3
y<-1:n
slp<-array(rnorm(n*73*144),c(3,73,144))
n.1<-length(y)-1
print(system.time({
rData <- array(0,c(73,144)) # array to store results
for (i in 1:73) {
for (j in 1:144) {
rData[i,j] <- cor(slp[,i,j],y)
}
}
}))
print(system.time({
n.1<-length(y)-1
mean.slp<-apply(slp,c(2,3),mean)
mean.y<-mean(y); sy<-var(y)^0.5
sqslp<-apply(slp*slp,c(2,3),sum)/n.1-mean.slp^2*n/n.1
sslpy<-apply(slp*y,c(2,3),sum)/n.1-mean.slp*mean.y*n/n.1
rslpy<-sslpy/(sqslp^0.5*sy)
}))
print(all(round(100*rslpy)==round(100*rData)))
@
output-start
[1] 1.49 0.00 1.49 0.00 0.00
[1] 0.92 0.00 0.92 0.00 0.00
[1] TRUE
output-end
Peter Wolf
Uwe Ligges wrote:
> Maurice McHugh wrote:
>
>> Hello everyone-
>>
>> I have a 3-d array with the 1st dimension being monthly mean data that
>> I would like to correlate with some time series index, for example,
>> and save the coefficients in an array.
>>
>> The code I am currently running is....
>>
>>
>> rData <- array(0,c(73,144)) # array to store results
>> for (i in 1:73) {
>> for (j in 1:144) {
>> rData[i,j] <- cor(slp[,i,j],y)
>> }
>> }
>>
>> Rather than running this analysis embedded with two outer loops,
>> are =
>> there any more efficient ways of doing this?
>> Many thanks!
>
>
>
> Don't know whether it's more efficient:
> You can try to apply() the function rcorr() in package "Hmisc" to your
> problem...
>
> Uwe Ligges
>
>
>
>
>>
>> Maurice
>>
>> Maurice McHugh
>> Department of Geography and Anthropology
>> Louisiana State University
>> Baton Rouge, LA
>> [[alternative HTML version deleted]]
>>
>> ______________________________________________
>> R-help at stat.math.ethz.ch mailing list
>> https://www.stat.math.ethz.ch/mailman/listinfo/r-help
>> PLEASE do read the posting guide!
>> http://www.R-project.org/posting-guide.html
>
>
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> https://www.stat.math.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide!
> http://www.R-project.org/posting-guide.html
More information about the R-help
mailing list