# [R] Car.proper C[] matrix

Jason Gasper Jason.Gasper at noaa.gov
Tue Sep 16 22:08:42 CEST 2008

Here is the WinBUGS code

model {
for(i in 1:N) {m[i] <- 1/n[ind[i]] }
cumsum[1] <- 0
for(i in 2:(N+1)) {cumsum[i] <- sum(num[1:(i-1)]) }
for(k in 1:sumNumNeigh) {
for(i in 1:N) {
# #pick[k,i] = 1 if cumsum[i] < k <= cumsum[i=1]; otherwise, pick[k,i] = 0
##step(e) 1 if e >= 0; 0 otherwise
pick[k,i]<-step(k-cumsum[i]-epsilon)*step(cumsum[i+1]-k) }

C[k]<-1/ inprod(num[], pick[k,]) }
epsilon <- 0.0001

Uwe Ligges wrote:
> If you want that people help to translate *code*, you have to specify
> it ...
>
> Uwe Ligges
>
>
> Jason Gasper wrote:
>> I am hoping someone can help translate some WinBUGS code into R code.
>> I would like to use R to create the C[] matrix required for a
>> car.proper model in WinBUGS, but I am having a difficult time
>> negotiating the coding. The C matrix provides normalized weights for
>> each pair of spatial areas.   So the WinBUGS example is as follows:
>>
>> # of the weight matrix with elements Cij. The first J1 elements of
>> the C[] vector contain the
>> # weights for the J1 neighbours of area i=1; the (J1+1) to J2
>> elements of the C[] vector contain
>> # the weights for the J2 neighbours of area i=2; etc.
>> # To set up this vector, we need to define a variable cumsum, which
>> gives the values of J1,
>> # J2, etc.; we then set up an index matrix pick[,] with N columns
>> corresponding to the
>> # i=1,...,N areas, and with the same number of rows as there are
>> elements in the C[] vector
>> # (i.e. sumNumNeigh). The elements C[ (cumsum[i]+1):cumsum[i+1] ]
>> correspond to
>> # the set of weights Cij associated with area i, and so we set up ith
>> column of the matrix pick[,]
>> # to have a 1 in all the rows k for which cumsum[i] < k <=
>> cumsum[i+1], and 0's elsewhere.
>> # For example, let N=4 and cumsum=c(0,3,5,6,8), so area i=1 has 3
>> neighbours, area i=2 has 2
>> # neighbours, area i=3 has 1 neighbour and area i=4 has 2 neighbours.
>> The the matrix pick[,] is:
>> # pick
>> # 1, 0, 0, 0,
>> # 1, 0, 0, 0,
>> # 1, 0, 0, 0,
>> # 0, 1, 0, 0,
>> # 0, 1, 0, 0,
>> # 0, 0, 1, 0,
>> # 0, 0, 0, 1,
>> # 0, 0, 0, 1,
>> #
>> # We can then use the inner product (inprod(,)) function in WinBUGS
>> and the kth row of pick to
>> # select which area corresponds to the kth element in the vector C[];
>> likewise, we can use inprod(,)
>> # and the ith column of pick to select the elements of C[] which
>> correspond to area i.
>>
>> Basically I want to do this in R to speed things up a little. Has
>> anyone written a function for this conversion?
>>
>> ______________________________________________
>> R-help at r-project.org mailing list
>> https://stat.ethz.ch/mailman/listinfo/r-help
>> http://www.R-project.org/posting-guide.html
>> and provide commented, minimal, self-contained, reproducible code.

--
Jason Gasper
National Marine Fisheries Service