5 mind <- function(d) {
6 n <- nrow(d)
7 add a column to identify row number for apply()
8 dd <- cbind(d,1:n)
9 wmins <- apply(dd[-n,],1,imin)
10 wmins will be 2xn, 1st row being indices and 2nd being values
11 i <- which.min(wmins[1,])
12 j <- wmins[2,i]
13 return(c(d[i,j],i,j))
14 }
15
16 finds the location, value of the minimum in a row x
17 imin <- function(x) {
18 n <- length(x)
19 i <- x[n]
20 j <- which.min(x[(i+1):(n-1)])
21 return(c(j,x[j]))
22 }
Let’s use R’s debugging tools to find and fix the problems.
We’ll run it first on a small test case:
> source("cities.R")
> m <- rbind(c(0,12,5),c(12,0,8),c(5,8,0))
>m
[,1] [,2] [,3]
[1,] 0 12 5
[2,] 12 0 8
[3,]580
> mind(m)
Error in mind(m) : subscript out of bounds
Not an auspicious start! Unfortunately, the error message doesn’t tell us
where the code blew up. But the debugger will give us that information:
> options(error=recover)
> mind(m)
Error in mind(m) : subscript out of bounds
Enter a frame number, or 0 to exit
1: mind(m)
Selection: 1
Called from: eval(expr, envir, enclos)
Browse[1]> where
296 Chapter 13