[R] Subtract matrices within arrays along indices
Etienne B. Racine
etiennebr at gmail.com
Wed Jul 29 15:41:13 CEST 2009
Hi Christian,
Christian Langkamp wrote:
>
> I have the following array: 3 dimensional object, one dimension being
> year. Object is 3*3*3
>
> library(plyr, reshape)
>
# reshape won't be loaded that way, use separate library()
Christian Langkamp wrote:
>
> a1<-rep(c(2007,2008,2009),9)
> a2<-c(rep("a",9),rep("b",9),rep("c",9))
> a3<-c(rep(c(rep(1,3),rep(2,3),rep(3,3)),3))
> a4 <- rnorm(27)
> A<-data.frame(cbind(comp=a2,val=a3, year=a1, a4))
>
# here, a4 have been switched to factor.
# you can use
str(A) #to check that
#so use nlevels(),
A$a4 <- as.numeric(a4)
Christian Langkamp wrote:
>
> A1<-melt(A, id=c("year", "comp", "val"))
> A2<-cast(A1, comp~val~year)
>
> I would now like to look for changes from one year to the other, i.e.
>
> "for(i in levels(A$year))
> A2[,,i]-A2[,,i-1]"
> and put that into A3.
>
# levels will return characters, but you can't substract 1 from it
# so use nlevels instead,
A3 <-array(dim=dim(A2))
for(i in 2:nlevels(A$year))
A3[,,i]<-A2[,,i]-A2[,,i-1]
Hope this help,
Etienne
Christian Langkamp wrote:
>
> Which should work except for the first one, i.e. giving me a 3*3*2 object
> A3.
>
> The more abstract formulation would possibly be cellwise operation within
> adjacent matrices of the array. I have however searched the forum for the
> key words and there is not much.
>
> Any help even in form of a reference would be appreciated.
>
--
View this message in context: http://www.nabble.com/Subtract-matrices-within-arrays-along-indices-tp24717178p24719544.html
Sent from the R help mailing list archive at Nabble.com.
More information about the R-help
mailing list