# [R] Help with Book example of Matrix application

Duncan Murdoch murdoch.duncan at gmail.com
Mon Apr 9 18:50:53 CEST 2012

```On 09/04/2012 12:32 PM, James Lenihan wrote:
> I found this example in an Introductory R book in the chapter on Matrices and
> Arrays

You should probably check with the author of the book (there might be an
errata page posted somewhere), but it looks like a typo, in your code or
the original:
>
> The array is
> >  m
>       [,1] [,2] [,3] [,4] [,5]
> [1,]    0   12   13    8   20
> [2,]   12    0   15   28   88
> [3,]   13   15    0    6    9
> [4,]    8   28    6    0   33
> [5,]   20   88    9   33    0
>
> The code is
>
> #returns the minimum value of d[i,j], i !=j and the row attaining
> #the minimum, for square symmetric d; no special policy on ties
> mind<- function(d) {
>       n<- nrow(d)
>       # add a column to identify row number for apply()
>       dd<- cbind(d,1:n)
>       wmins<- apply(dd[-n,],1,imin)
>       # wins will be 2 X n, 1st row being indices and 2nd being values
>       i<- which.min(wmins[2,])
>       j<- wmins[1,i]
>       return(c(d[i,j],i,j))
> }
>
> #this finds the location, value of the minimum in a row x
> imin<- function(x) {
>     lx<- length(x)
>      i<- x[lx] # original row number
>      j<-which.min(x[(x+1):(lx-1)])

That line doesn't make sense.  Putting i in place of the innermost x
would make more sense, but wouldn't work in all cases:  if i == lx,
you'll get a garbage answer.

Duncan Murdoch
>      k<- i+j
>      return(c(k,x[k]))
> }
> The result s/b
> [1] 6 3 4
>
> I am getting:
>
> Warning messages:
> 1: In (x + 1):(lx - 1) :
>    numerical expression has 6 elements: only the first used
> 2: In (x + 1):(lx - 1) :
>    numerical expression has 6 elements: only the first used
> 3: In (x + 1):(lx - 1) :
>    numerical expression has 6 elements: only the first used
> 4: In (x + 1):(lx - 1) :
>    numerical expression has 6 elements: only the first used
>
> I have check my typing a number of times.
>
> Does anyone see an error?
>
> Thanks,
>
> Jim L.
> 	[[alternative HTML version deleted]]
>
> ______________________________________________
> R-help at r-project.org 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.

```