R
    Tokyo.R #16 (2011/08/27)
                   @a_bicky
• Takeshi Arabiki                                1

    ‣ Twitter: @a_bicky
    ‣        : id:a_bicky

•
                              R

•
                http://d.hatena.ne.jp/a_bicky/
Osaka.R #4




http://www.slideshare.net/abicky/twitterr   http://www.slideshare.net/abicky/introduction-to-hadoop-mapreduce
• R debugger
•
•
•
• ksvm
•
•
debug



                                      : http://ja.wikipedia.org/wiki/




http://getfirebug.com/whatisfirebug



                 R
R debugger
R debugger
‣ R debugger
‣
‣
‣
‣
‣
‣
R debugger
                                                                           Perl
                                             R debugger            gdb
                                                                         debugger

                                                 where             bt       T

                                                   n               n        n

                                         debugonce(func※); c        s       s

                                         browserSetDebug(); c      fin       r

                                                   c                c       c

                                                  Q                q        q
                                                       ※func


<RET>           debug      n   browser       c                 n                n
options(browserNLdisabled = TRUE)                <RET>
browser
f <- function(x) {
    y <- x * 2
    browser()   #
     z <- y^2
     return(z)
}
browser
f <- function(x) {   > f(10)
    y <- x * 2       Called from: f(10)
                     Browse[1]>
     z <- y^2
     return(z)
}
browser
f <- function(x) {   > f(10)
    y <- x * 2       Called from: f(10)
                     Browse[1]> ls()
     z <- y^2        [1] "x" "y"
     return(z)       Browse[1]>
}
browser
f <- function(x) {   > f(10)
    y <- x * 2       Called from: f(10)
                     Browse[1]> ls()
     z <- y^2        [1] "x" "y"
     return(z)       Browse[1]> n #
}                    debug: z <- y^2
                     Browse[2]>
browser
f <- function(x) {   > f(10)
    y <- x * 2       Called from: f(10)
                     Browse[1]> ls()
     z <- y^2        [1] "x" "y"
     return(z)       Browse[1]> n #
}                    debug: z <- y^2
                     Browse[2]> z
                     Error: object 'z' not found
                     Browse[2]>



                                z
browser
f <- function(x) {             > f(10)
    y <- x * 2                 Called from: f(10)
                               Browse[1]> ls()
     z <- y^2                  [1] "x" "y"
     return(z)                 Browse[1]> n #
}                              debug: z <- y^2
                               Browse[2]> z
                               Error: object 'z' not found
                               Browse[2]> n
                               debug: return(z)
                               Browse[2]> z
                               [1] 400
                               Browse[2]>


                     z   y^2
browser
f <- function(x) {           > f(10)
    y <- x * 2               Called from: f(10)
                             Browse[1]> ls()
     z <- y^2                [1] "x" "y"
     return(z)               Browse[1]> n #
}                            debug: z <- y^2
                             Browse[2]> z
                             Error: object 'z' not found
                             Browse[2]> n
                             debug: return(z)
                             Browse[2]> z
                             [1] 400
                             Browse[2]> z <- 1 # z
                             Browse[2]> n
                             [1] 1
                             >

                 f(10)   z
debug
f <- function(x) {      > debug(f)
    y <- x * 2          > f(10)
    z <- y^2            debugging in: f(10)
    return(z)           debug: {
}                           y <- x * 2
                            z <- y^2
                            return(z)
                        }
                        Browse[2]> n
                        debug: y <- x * 2
              browser   Browse[2]> n
                        debug: z <- y^2
                        Browse[2]> n
                        debug: return(z)
                        Browse[2]> n
                        exiting from: f(10)
                        [1] 400
                        >
debugonce
> debug(f)            > debugonce(f)
> f(10)               > f(10)
debugging in: f(10)   debugging in: f(10)
debug: {              debug: {
    y <- x * 2            y <- x * 2
    z <- y^2              z <- y^2
    return(z)             return(z)
}                     }
Browse[2]> Q #        Browse[2]> Q #
> isdebugged(f)       > isdebugged(f)
[1] TRUE              [1] FALSE
> f(10)               > f(10)
debugging in: f(10)   [1] 400
...                   >




※ undebug(f)
traceback
f <- function(x) {         > f(1:5)
    x <- as.character(x)   Error in sum(x) : invalid
    return(g(x))           'type' (character) of argument
}                          > traceback()
                           3: h(x)     h
g <- function(x) {         2: g(x)
    if (length(x) > 1) {   1: f(1:10)
        return(h(x))       > debug(h)
    } else {               > f(1:10)
        return(x)          debugging in: h(x)
    }                      debug: {
}                               return(sum(x))
                           }
h <- function(x) {         Browse[2]> x
    return(sum(x))           [1] "1" "2" "3" "4" "5"
}                          Browse[2]> sum(x)
                           Error in sum(x) : invalid
                           'type' (character) of argument
browser
f <- function(x) {           > f(5) # y = 10
    y <- x * 2               [1] 100
    browser(expr = y > 10)   > f(10) # y = 20
    z <- y^2                 Called from: f(10)
    return(z)                Browse[1]>
}




f <- function(x) {
    y <- x * 2
    if (y > 10) {
        browser()
    }
    z <- y^2
    return(z)
}
browserText
f <- function(x) {      > f(10)
    browser("1st bt")   Called from: f(10)
                        Browse[1]> where #
    # <   >
                        where 1: f(10)
    browser("2nd bt")
}
                        Browse[1]> browserText()
                        [1] "1st bt"
                        Browse[1]> c
                        Called from: f(10)
                        Browse[1]> where #
                        where 1: f(10)

                        Browse[1]> browserText()
                        [1] "2nd bt"
‣
‣
‣
head
> head(iris)    #                  6
    Sepal.Length Sepal.Width Petal.Length Petal.Width Species
1            5.1         3.5          1.4         0.2 setosa
2            4.9         3.0          1.4         0.2 setosa
3            4.7         3.2          1.3         0.2 setosa
4            4.6         3.1          1.5         0.2 setosa
5            5.0         3.6          1.4         0.2 setosa
6            5.4         3.9          1.7         0.4 setosa
>   head(iris, 3) #       3
  Sepal.Length Sepal.Width Petal.Length Petal.Width Species
1          5.1         3.5          1.4         0.2 setosa
2          4.9         3.0          1.4         0.2 setosa
3          4.7         3.2          1.3         0.2 setosa
>


※                        tail
summary
> summary(m <- lm(weight ~ group, PlantGrowth))

Call:
lm(formula = weight ~ group, data = PlantGrowth)

Residuals:
    Min      1Q Median        3Q      Max
-1.0710 -0.4180 -0.0060   0.2627   1.3690

Coefficients:
            Estimate Std. Error t value Pr(>|t|)
(Intercept)    5.0320    0.1971 25.527    <2e-16 ***
grouptrt1     -0.3710    0.2788 -1.331    0.1944
grouptrt2      0.4940    0.2788   1.772   0.0877 .
---
Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1

Residual standard error: 0.6234 on 27 degrees of freedom
Multiple R-squared: 0.2641,	 Adjusted R-squared: 0.2096
F-statistic: 4.846 on 2 and 27 DF, p-value: 0.01591
str
> m    # print.lm(m)

Call:
lm(formula = weight ~ group, data = PlantGrowth)

Coefficients:
(Intercept)      grouptrt1     grouptrt2
      5.032         -0.371         0.494



> str(m)
List of 13
 $ coefficients : Named num [1:3] 5.032 -0.371 0.494
  ..- attr(*, "names")= chr [1:3] "(Intercept)" "grouptrt1"
"grouptrt2"


> m$coefficients       #
(Intercept)     grouptrt1    grouptrt2
      5.032        -0.371        0.494
class
> class(m)
[1] "lm"




data.frame                  matrix
character                  factor

> (x <- c(b    = "this is b", a = "this is a"))
           b             a
"this is b"    "this is a"
> (index <-    factor(c("a", "b")))
[1] a b
Levels: a b
> x[index]     #
          b           a
"this is b" "this is a"
> x[as.character(index)]     #
          a           b
"this is a" "this is b"
coef
> m$coefficients
(Intercept)   grouptrt1   grouptrt2
      5.032      -0.371       0.494
> coef(m)
(Intercept)   grouptrt1   grouptrt2
      5.032      -0.371       0.494
showMethods
> coef
standardGeneric for "coef" defined from package "stats"

function (object, ...)
standardGeneric("coef")
<environment: 0x100f8d4a0>
Methods may be defined for arguments: object
Use showMethods("coef") for currently available ones.
> showMethods("coef") # coef
Function: coef (package stats)
object="ANY"
object="gausspr"
object="kfa"
object="kqr"                lm
object="ksvm"
object="lm"
                            selectMethod
    (inherited from: object="ANY")
object="lssvm"
object="rvm"
selectMethod, methods
> selectMethod("coef", signature = "lm")   # signature
Method Definition (Class "derivedDefaultMethod"):

function (object, ...)
UseMethod("coef")
<environment: namespace:stats>

Signatures:
        object
target "ANY"
defined "ANY"
> methods(coef)   # UseMethod                methods
[1] coef.aov*      coef.Arima*   coef.default* coef.listof*
coef.nls*

   Non-visible functions are asterisked
> coef.default # coef.lm           coef.default
Error: object 'coef.default' not found
selectMethod, methods
> selectMethod("coef", signature = "lm")   # signature
Method Definition (Class "derivedDefaultMethod"):

function (object, ...)
UseMethod("coef")
<environment: namespace:stats>

Signatures:
        object
target "ANY"
defined "ANY"
> methods(coef)   # UseMethod                  methods
[1] coef.aov*      coef.Arima*   coef.default* coef.listof*
coef.nls*
                                           *
   Non-visible functions are asterisked
> coef.default # coef.lm           coef.default
Error: object 'coef.default' not found
package:::func
> stats:::coef.default   # Non-visible   pkg:::func
function (object, ...)
object$coefficients
<environment: namespace:stats>
> evalq(coef.default, environment(lm))   #
function (object, ...)
object$coefficients
<environment: namespace:stats>




> debug(stats:::coef.default)
> coef(m)
debugging in: coef.default(m)
debug: object$coefficients
Browse[2]>
‣ trace
‣ recover
‣ options(error = recover)
‣ options(error = dump.frames)
trace
 trace
trace(what, tracer, exit, at, print, signature,
      where = topenv(parent.frame()), edit = FALSE)

what:
tracer:
exit:
at:
print:
signature:
where:
edit:
trace
     trace                      3      5

f <- function(x) {                  > trace(f, browser, at = c(3, 5))
    cat("1st linen")               > f()
    if (TRUE) {                     1st line
        cat("1st 2nd linen")       Tracing f() step 3
        cat("2nd 2nd linen")       Called from: eval(expr, envir,
    }                               enclos)
                                    Browse[1]> c
     cat("3rd line                  1st 2nd line
")                                  2nd 2nd line
     cat("4th linen")              3rd line
}                                   Tracing f() step 5
                                    Called from: eval(expr, envir,
                                    enclos)
                                    Browse[1]> c
                                    4th line
trace
     trace                      3      5

f <- function(x) {                  > trace(f, browser, at = c(3, 5))
    cat("1st linen")               > f()
    if (TRUE) {                     1st line
        cat("1st 2nd linen")       Tracing f() step 3
        cat("2nd 2nd linen")       Called from: eval(expr, envir,
    }                               enclos)
                                    Browse[1]> c
     cat("3rd line                  1st 2nd line
")                                  2nd 2nd line
     cat("4th linen")              3rd line
}                                   Tracing f() step 5
                                    Called from: eval(expr, envir,
                                    enclos)
                                    Browse[1]> c
                                    4th line
trace
     trace                                         f

f <- function(x) {            # 1   > untrace(f)       # trace
    cat("1st linen")         # 2   > as.list(body(f))
    if (TRUE) {               # 3   [[1]]
        cat("1st 2nd linen")       `{`
        cat("2nd 2nd linen")
    } # 1             1             [[2]]
#                                   cat("1st linen")
     cat("3rd line
                                    [[3]]
")   #      1                 # 4
                                    if (TRUE) {
     cat("4th linen")        # 5       cat("1st 2nd linen")
}
                                        cat("2nd 2nd linen")
                                    }

                                    [[4]]
                                    cat("3rd linen")

                                    [[5]]
                                    cat("4th linen")
trace
     trace                           trace

f <- function(x) {              > trace(f, browser, at = c(3, 5))
    cat("1st linen")           [1] "f"
    if (TRUE) {                 > body(f)
        cat("1st 2nd linen")   {
        cat("2nd 2nd linen")     cat("1st linen")
    }                             {
                                    .doTrace(browser(), "step 3")
     cat("3rd line                  if (TRUE) {
")                                    cat("1st 2nd linen")
     cat("4th linen")                cat("2nd 2nd linen")
}                                   }
                                  }
                                  cat("3rd linen")
                                  {
                                    .doTrace(browser(), "step 5")
                                    cat("4th linen")
                                  }
                                }
trace
     trace                           trace

f <- function(x) {              > trace(f, browser, at = c(3, 5))
    cat("1st linen")           [1] "f"
    if (TRUE) {                 > body(f)
        cat("1st 2nd linen")   {
        cat("2nd 2nd linen")     cat("1st linen")
    }                             {            .doTrace
                                    .doTrace(browser(), "step 3")
     cat("3rd line                  if (TRUE) {
")                                    cat("1st 2nd linen")
     cat("4th linen")                cat("2nd 2nd linen")
}                                   }
                                  }
                                  cat("3rd linen")
                                  {
                                    .doTrace(browser(), "step 5")
                                    cat("4th linen")
                                  }
                                }
trace
     trace                         trace

f <- function(x) {              > f()
    cat("1st linen")           1st line
    if (TRUE) {                 Tracing f() step 3
        cat("1st 2nd linen")   Called from: eval(expr, envir,
        cat("2nd 2nd linen")   enclos)
    }                           Browse[1]> Q
                                > # .doTrace
     cat("3rd line              > tracingState(FALSE)
")                              [1] TRUE
     cat("4th linen")          > f()
}                               1st line
                                1st 2nd line
                                2nd 2nd line
                                3rd line
                                4th line
                                > # .doTrace
                                > tracingState(TRUE)
                                [1] FALSE
trace
     trace
f <- function(x) {              > trace(f, edit = TRUE)   # f
    cat("1st linen")           Waiting for Emacs...
    if (TRUE) {                 [1] "f"
        cat("1st 2nd linen")   > body(f)
        cat("2nd 2nd linen")   {
    }                               cat("1st linen")
                                    cat("3rd linen")
     cat("3rd line                  browser()
")                                  cat("4th linen")
     cat("4th linen")          }
}                               > f()
                                1st line
                                3rd line
                                Called from: f()
f <- function(x) {              Browse[1]>
    cat("1st linen")
    cat("3rd linen")             ※ .doTrace
    browser()
    cat("4th linen")            tracingState
}
recover

  recover
f <- function(x) {         > f(1)
    x <- g(x)
    return(x)              Enter a frame number, or 0 to exit
}
                           1: f(1)
g <- function(x) {         2: g(x)
    y <- x + 1             3: h(y)
    y <- h(y)
    return(y)              Selection: 1   # f(1)
}                          Called from: top level
                           Browse[1]> x
h <- function(y) {         [1] 1
    z <- y + 1
    recover()
    return(z)
}
recover

  recover
f <- function(x) {         Browse[1]> c
    x <- g(x)
    return(x)              Enter a frame number, or 0 to exit
}
                           1: f(1)
g <- function(x) {         2: g(x)
    y <- x + 1             3: h(y)
    y <- h(y)
    return(y)              Selection: 2   # g(x)
}                          Called from: f(1)
                           Browse[1]> y
h <- function(y) {         [1] 2
    z <- y + 1
    recover()
    return(z)
}
recover

  recover
f <- function(x) {         Browse[1]> c
    x <- g(x)
    return(x)              Enter a frame number, or 0 to exit
}
                           1: f(1)
g <- function(x) {         2: g(x)
    y <- x + 1             3: h(y)
    y <- h(y)
    return(y)              Selection: 3   # h(y)
}                          Called from: g(x)
                           Browse[1]> z
h <- function(y) {         [1] 3
    z <- y + 1
    recover()
    return(z)
}
options(error = recover)

  recover                                recover

f <- function(x) {       > options(error = recover)
    x <- g(x)            > f(1)
    return(x)            Error in print(x) : object 'x' not
}                        found

g <- function(x) {       Enter a frame number, or 0 to exit
    y <- x + 1
    y <- h(y)            1:   f(1)
    return(y)            2:   g(x)
}                        3:   h(y)
                         4:   print(x)
h <- function(y) {
    z <- y + 1           Selection: 3 # h(y)
    print(x) # Error!    Called from: h(y)
    return(z)            Browse[1]> x
}                        Error during wrapup: object 'x'
                         not found
                         Browse[1]> ls()
                         [1] "y" "z"
options(error = dump.frames)
                                   dump.frames
dump.frames             recover
f <- function(x) {       > options(error = dump.frames)
    x <- g(x)            > f(1)
    return(x)            Error in print(x) : object 'x' not
}                        found
                         > ls()
g <- function(x) {       [1] "f"   "g"   "h"   "last.dump"
    y <- x + 1           > debugger(last.dump)
    y <- h(y)            Message: Error in print(x) :
    return(y)            object 'x' not found
}                        Available environments had calls:
                         1: f(1)
h <- function(y) {       2: g(x)
    z <- y + 1           3: h(y)
    print(x) # Error!    4: print(x)
    return(z)
}                        Enter an environment number, or 0
                         to exit Selection:
ksvm
ksvm

> library(kernlab)
> ksvm(Species ~ .,
+      iris,
+      class.weights = c(versicolor = 1, setosa = 10),
+      prob.model = TRUE)
Using automatic sigma estimation (sigest) for RBF or laplace
kernel
Error in lev(ret)[yd[cind]] :
  only 0's may be mixed with negative subscripts
ksvm

> options(error = recover)    # recover
> ksvm(Species ~ .,
+      iris,
+      class.weights = c(versicolor = 1, setosa = 10),
+      prob.model = TRUE)
Using automatic sigma estimation (sigest) for RBF or laplace kernel
Error in lev(ret)[yd[cind]] :
  only 0's may be mixed with negative subscripts

Enter a frame number, or 0 to exit

 1: ksvm(Species ~ ., iris, class.weights = c(versicolor = 1, setosa
= 10), pro
 <   >
 9:   .local(x, ...)
10:   as.factor(lev(ret)[yd[cind]])
11:   is.factor(x)
12:   inherits(x, "factor")

Selection: 10
ksvm

Called from: top level
Browse[1]> ls()
[1] "x"
Browse[1]> x
Error during wrapup: promise already under evaluation: recursive
default argument reference or earlier problems?
ksvm

Called from: top level
Browse[1]> ls()
[1] "x"
Browse[1]> x
Error during wrapup: promise already under evaluation: recursive
default argument reference or earlier problems?
ksvm
> options(error = NULL)
> ksvm(Species ~ .,
+      iris,
+      class.weights = c(versicolor = 1, setosa = 10),
+      prob.model = TRUE)
Using automatic sigma estimation (sigest) for RBF or laplace kernel
Error in lev(ret)[yd[cind]] :
  only 0's may be mixed with negative subscripts
> ksvm #
standardGeneric for "ksvm" defined from package "kernlab"

function (x, ...)
standardGeneric("ksvm")
<environment: 0x103623e08>
Methods may be defined for arguments: x
Use showMethods("ksvm") for currently available ones.



                      S4
ksvm

> showMethods("ksvm")
Function: ksvm (package kernlab)
x="formula"
x="kernelMatrix"
x="list"
x="matrix"
x="vector"

> selectMethod(ksvm, "formula")
Method Definition:

function (x, ...)
{
    .local <- function (x, data = NULL, ..., subset, na.action =
na.omit,
         scaled = TRUE)
  <  >
         ret <- ksvm(x, y, scaled = scaled, ...)
 <   >


     signature      matrix     ksvm
ksvm


> selectMethod(ksvm, "matrix")
Method Definition:

function (x, ...)
{
    .local <- function (x, y = NULL, scaled = TRUE, type = NULL,
        kernel = "rbfdot", kpar = "automatic", C = 1, nu = 0.2,

 <   >
                        , drop = FALSE][cind, ], as.factor(lev(ret)
[yd[cind]]),
 <   >
ksvm

> trace(ksvm, signature = “matrix”, edit = TRUE)



                           browser

                      browser()
                      if (is.null(class.weights))
                        cret <- ksvm(x[c(indexes[[i]], indexes
[[j]]),
                          , drop = FALSE][cind, ], yd[cind],
                          type = type(ret), kernel = kernel,
                          kpar = NULL, C = C, nu = nu, tol = tol,
                          scaled = FALSE, cross = 0, fit = FALSE,
                          cache = cache, prob.model = FALSE)
                      else cret <- ksvm(x[c(indexes[[i]], indexes
[[j]]),
                        , drop = FALSE][cind, ], as.factor(lev(ret)
[yd[cind]]),
ksvm
> ksvm(Species ~ .,
+       iris,
+       class.weights = c(versicolor = 1, setosa = 10),
+       prob.model = TRUE)
Using automatic sigma estimation (sigest) for RBF or laplace kernel
Called from: .local(x, ...)
Browse[1]> yd
   [1] -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1
  [22] -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1
  [43] -1 -1 -1 -1 -1 -1 -1 -1 1 1 1 1 1 1 1 1 1 1 1 1 1
  [64] 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
  [85] 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1



 lev(ret)[yd[cind]]                              yd     (-1, 1)


      yd    lev(ret)
> 1:5
[1] 1 2 3 4 5
> .Last.value
[1] 1 2 3 4 5



 ESS   TAB      .Last.value
f <- function(x) {
    y <- x
    g(y)
}

g <- function(x) {
    x <- x^2
    browser()
}




> f(10)
Called from: g(y)    # x      y
Browse[1]> x         # x      2
[1] 100
Browse[1]> y         # y
Error: object 'y' not found
Browse[1]> evalq(y, parent.frame()) #      y
[1] 10
Browse[1]> evalq(ls(), parent.frame()) #
[1] "x" "y"




Browse[1]> eval.parent(quote(y))     #         part1
[1] 10
Browse[1]> get("y", parent.frame()) #          part2
[1] 10
Browse[1]> ls(envir = parent.frame()) #
[1] "x" "y"



       evalq(expr, parent.frame())
apply                    browser

f <- function() {
    a <- lapply(1:10000, function(x) {
        browser() # 1     browser()
         print(x)
    })
}
apply                      browser
> debug(f)
> f()
debugging in: f()
debug: {
    a <- lapply(1:10000, function(x) {
         browser()
         print(x)
    })
}
Browse[2]> n
debug: a <- lapply(1:10000, function(x) {
    browser()
    print(x)
})
Browse[2]>
Called from: FUN(1:10000[[1L]], ...)
Browse[2]> c
[1] 1
Called from: FUN(1:10000[[2L]], ...) #    browser()
Browse[2]>
apply                      browser
Browse[2]> evalq(FUN <- edit(FUN), parent.frame())
function(x) {
        browser() #
        print(x)
    }




Browse[2]> evalq(fix(FUN), parent.frame())



Browse[2]> FUN <<- evalq(edit(FUN), parent.frame())
R
•   HI!! http://kohske.wordpress.com/?s=r+debug
•   An Introduction to the Interactive Debugging Tools in R http://
    www.biostat.jhsph.edu/~rpeng/docs/R-debug-tools.pdf
•   Debugging in R http://www.stats.uwo.ca/faculty/murdoch/
    software/debuggingR/
•   Summer Computing 2011 Week 3:R debugging + misc http://
    www.stat.cmu.edu/~hseltman/711/Week3.pdf
•   Rdebug http://www.math.ncu.edu.tw/~chenwc/R_note/
    reference/debug/Rdebug.pdf

Rデバッグあれこれ

  • 1.
    R Tokyo.R #16 (2011/08/27) @a_bicky
  • 2.
    • Takeshi Arabiki 1 ‣ Twitter: @a_bicky ‣ : id:a_bicky • R • http://d.hatena.ne.jp/a_bicky/
  • 3.
    Osaka.R #4 http://www.slideshare.net/abicky/twitterr http://www.slideshare.net/abicky/introduction-to-hadoop-mapreduce
  • 4.
  • 5.
    debug : http://ja.wikipedia.org/wiki/ http://getfirebug.com/whatisfirebug R
  • 6.
  • 7.
    R debugger ‣ Rdebugger ‣ ‣ ‣ ‣ ‣ ‣
  • 8.
    R debugger Perl R debugger gdb debugger where bt T n n n debugonce(func※); c s s browserSetDebug(); c fin r c c c Q q q ※func <RET> debug n browser c n n options(browserNLdisabled = TRUE) <RET>
  • 9.
    browser f <- function(x){ y <- x * 2 browser() # z <- y^2 return(z) }
  • 10.
    browser f <- function(x){ > f(10) y <- x * 2 Called from: f(10) Browse[1]> z <- y^2 return(z) }
  • 11.
    browser f <- function(x){ > f(10) y <- x * 2 Called from: f(10) Browse[1]> ls() z <- y^2 [1] "x" "y" return(z) Browse[1]> }
  • 12.
    browser f <- function(x){ > f(10) y <- x * 2 Called from: f(10) Browse[1]> ls() z <- y^2 [1] "x" "y" return(z) Browse[1]> n # } debug: z <- y^2 Browse[2]>
  • 13.
    browser f <- function(x){ > f(10) y <- x * 2 Called from: f(10) Browse[1]> ls() z <- y^2 [1] "x" "y" return(z) Browse[1]> n # } debug: z <- y^2 Browse[2]> z Error: object 'z' not found Browse[2]> z
  • 14.
    browser f <- function(x){ > f(10) y <- x * 2 Called from: f(10) Browse[1]> ls() z <- y^2 [1] "x" "y" return(z) Browse[1]> n # } debug: z <- y^2 Browse[2]> z Error: object 'z' not found Browse[2]> n debug: return(z) Browse[2]> z [1] 400 Browse[2]> z y^2
  • 15.
    browser f <- function(x){ > f(10) y <- x * 2 Called from: f(10) Browse[1]> ls() z <- y^2 [1] "x" "y" return(z) Browse[1]> n # } debug: z <- y^2 Browse[2]> z Error: object 'z' not found Browse[2]> n debug: return(z) Browse[2]> z [1] 400 Browse[2]> z <- 1 # z Browse[2]> n [1] 1 > f(10) z
  • 16.
    debug f <- function(x){ > debug(f) y <- x * 2 > f(10) z <- y^2 debugging in: f(10) return(z) debug: { } y <- x * 2 z <- y^2 return(z) } Browse[2]> n debug: y <- x * 2 browser Browse[2]> n debug: z <- y^2 Browse[2]> n debug: return(z) Browse[2]> n exiting from: f(10) [1] 400 >
  • 17.
    debugonce > debug(f) > debugonce(f) > f(10) > f(10) debugging in: f(10) debugging in: f(10) debug: { debug: { y <- x * 2 y <- x * 2 z <- y^2 z <- y^2 return(z) return(z) } } Browse[2]> Q # Browse[2]> Q # > isdebugged(f) > isdebugged(f) [1] TRUE [1] FALSE > f(10) > f(10) debugging in: f(10) [1] 400 ... > ※ undebug(f)
  • 18.
    traceback f <- function(x){ > f(1:5) x <- as.character(x) Error in sum(x) : invalid return(g(x)) 'type' (character) of argument } > traceback() 3: h(x) h g <- function(x) { 2: g(x) if (length(x) > 1) { 1: f(1:10) return(h(x)) > debug(h) } else { > f(1:10) return(x) debugging in: h(x) } debug: { } return(sum(x)) } h <- function(x) { Browse[2]> x return(sum(x)) [1] "1" "2" "3" "4" "5" } Browse[2]> sum(x) Error in sum(x) : invalid 'type' (character) of argument
  • 19.
    browser f <- function(x){ > f(5) # y = 10 y <- x * 2 [1] 100 browser(expr = y > 10) > f(10) # y = 20 z <- y^2 Called from: f(10) return(z) Browse[1]> } f <- function(x) { y <- x * 2 if (y > 10) { browser() } z <- y^2 return(z) }
  • 20.
    browserText f <- function(x){ > f(10) browser("1st bt") Called from: f(10) Browse[1]> where # # < > where 1: f(10) browser("2nd bt") } Browse[1]> browserText() [1] "1st bt" Browse[1]> c Called from: f(10) Browse[1]> where # where 1: f(10) Browse[1]> browserText() [1] "2nd bt"
  • 22.
  • 23.
    head > head(iris) # 6 Sepal.Length Sepal.Width Petal.Length Petal.Width Species 1 5.1 3.5 1.4 0.2 setosa 2 4.9 3.0 1.4 0.2 setosa 3 4.7 3.2 1.3 0.2 setosa 4 4.6 3.1 1.5 0.2 setosa 5 5.0 3.6 1.4 0.2 setosa 6 5.4 3.9 1.7 0.4 setosa > head(iris, 3) # 3 Sepal.Length Sepal.Width Petal.Length Petal.Width Species 1 5.1 3.5 1.4 0.2 setosa 2 4.9 3.0 1.4 0.2 setosa 3 4.7 3.2 1.3 0.2 setosa > ※ tail
  • 24.
    summary > summary(m <-lm(weight ~ group, PlantGrowth)) Call: lm(formula = weight ~ group, data = PlantGrowth) Residuals: Min 1Q Median 3Q Max -1.0710 -0.4180 -0.0060 0.2627 1.3690 Coefficients: Estimate Std. Error t value Pr(>|t|) (Intercept) 5.0320 0.1971 25.527 <2e-16 *** grouptrt1 -0.3710 0.2788 -1.331 0.1944 grouptrt2 0.4940 0.2788 1.772 0.0877 . --- Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1 Residual standard error: 0.6234 on 27 degrees of freedom Multiple R-squared: 0.2641, Adjusted R-squared: 0.2096 F-statistic: 4.846 on 2 and 27 DF, p-value: 0.01591
  • 25.
    str > m # print.lm(m) Call: lm(formula = weight ~ group, data = PlantGrowth) Coefficients: (Intercept) grouptrt1 grouptrt2 5.032 -0.371 0.494 > str(m) List of 13 $ coefficients : Named num [1:3] 5.032 -0.371 0.494 ..- attr(*, "names")= chr [1:3] "(Intercept)" "grouptrt1" "grouptrt2" > m$coefficients # (Intercept) grouptrt1 grouptrt2 5.032 -0.371 0.494
  • 26.
    class > class(m) [1] "lm" data.frame matrix character factor > (x <- c(b = "this is b", a = "this is a")) b a "this is b" "this is a" > (index <- factor(c("a", "b"))) [1] a b Levels: a b > x[index] # b a "this is b" "this is a" > x[as.character(index)] # a b "this is a" "this is b"
  • 28.
    coef > m$coefficients (Intercept) grouptrt1 grouptrt2 5.032 -0.371 0.494 > coef(m) (Intercept) grouptrt1 grouptrt2 5.032 -0.371 0.494
  • 29.
    showMethods > coef standardGeneric for"coef" defined from package "stats" function (object, ...) standardGeneric("coef") <environment: 0x100f8d4a0> Methods may be defined for arguments: object Use showMethods("coef") for currently available ones. > showMethods("coef") # coef Function: coef (package stats) object="ANY" object="gausspr" object="kfa" object="kqr" lm object="ksvm" object="lm" selectMethod (inherited from: object="ANY") object="lssvm" object="rvm"
  • 30.
    selectMethod, methods > selectMethod("coef",signature = "lm") # signature Method Definition (Class "derivedDefaultMethod"): function (object, ...) UseMethod("coef") <environment: namespace:stats> Signatures: object target "ANY" defined "ANY" > methods(coef) # UseMethod methods [1] coef.aov* coef.Arima* coef.default* coef.listof* coef.nls* Non-visible functions are asterisked > coef.default # coef.lm coef.default Error: object 'coef.default' not found
  • 31.
    selectMethod, methods > selectMethod("coef",signature = "lm") # signature Method Definition (Class "derivedDefaultMethod"): function (object, ...) UseMethod("coef") <environment: namespace:stats> Signatures: object target "ANY" defined "ANY" > methods(coef) # UseMethod methods [1] coef.aov* coef.Arima* coef.default* coef.listof* coef.nls* * Non-visible functions are asterisked > coef.default # coef.lm coef.default Error: object 'coef.default' not found
  • 32.
    package:::func > stats:::coef.default # Non-visible pkg:::func function (object, ...) object$coefficients <environment: namespace:stats> > evalq(coef.default, environment(lm)) # function (object, ...) object$coefficients <environment: namespace:stats> > debug(stats:::coef.default) > coef(m) debugging in: coef.default(m) debug: object$coefficients Browse[2]>
  • 34.
    ‣ trace ‣ recover ‣options(error = recover) ‣ options(error = dump.frames)
  • 35.
    trace trace trace(what, tracer,exit, at, print, signature, where = topenv(parent.frame()), edit = FALSE) what: tracer: exit: at: print: signature: where: edit:
  • 36.
    trace trace 3 5 f <- function(x) { > trace(f, browser, at = c(3, 5)) cat("1st linen") > f() if (TRUE) { 1st line cat("1st 2nd linen") Tracing f() step 3 cat("2nd 2nd linen") Called from: eval(expr, envir, } enclos) Browse[1]> c cat("3rd line 1st 2nd line ") 2nd 2nd line cat("4th linen") 3rd line } Tracing f() step 5 Called from: eval(expr, envir, enclos) Browse[1]> c 4th line
  • 37.
    trace trace 3 5 f <- function(x) { > trace(f, browser, at = c(3, 5)) cat("1st linen") > f() if (TRUE) { 1st line cat("1st 2nd linen") Tracing f() step 3 cat("2nd 2nd linen") Called from: eval(expr, envir, } enclos) Browse[1]> c cat("3rd line 1st 2nd line ") 2nd 2nd line cat("4th linen") 3rd line } Tracing f() step 5 Called from: eval(expr, envir, enclos) Browse[1]> c 4th line
  • 38.
    trace trace f f <- function(x) { # 1 > untrace(f) # trace cat("1st linen") # 2 > as.list(body(f)) if (TRUE) { # 3 [[1]] cat("1st 2nd linen") `{` cat("2nd 2nd linen") } # 1 1 [[2]] # cat("1st linen") cat("3rd line [[3]] ") # 1 # 4 if (TRUE) { cat("4th linen") # 5 cat("1st 2nd linen") } cat("2nd 2nd linen") } [[4]] cat("3rd linen") [[5]] cat("4th linen")
  • 39.
    trace trace trace f <- function(x) { > trace(f, browser, at = c(3, 5)) cat("1st linen") [1] "f" if (TRUE) { > body(f) cat("1st 2nd linen") { cat("2nd 2nd linen") cat("1st linen") } { .doTrace(browser(), "step 3") cat("3rd line if (TRUE) { ") cat("1st 2nd linen") cat("4th linen") cat("2nd 2nd linen") } } } cat("3rd linen") { .doTrace(browser(), "step 5") cat("4th linen") } }
  • 40.
    trace trace trace f <- function(x) { > trace(f, browser, at = c(3, 5)) cat("1st linen") [1] "f" if (TRUE) { > body(f) cat("1st 2nd linen") { cat("2nd 2nd linen") cat("1st linen") } { .doTrace .doTrace(browser(), "step 3") cat("3rd line if (TRUE) { ") cat("1st 2nd linen") cat("4th linen") cat("2nd 2nd linen") } } } cat("3rd linen") { .doTrace(browser(), "step 5") cat("4th linen") } }
  • 41.
    trace trace trace f <- function(x) { > f() cat("1st linen") 1st line if (TRUE) { Tracing f() step 3 cat("1st 2nd linen") Called from: eval(expr, envir, cat("2nd 2nd linen") enclos) } Browse[1]> Q > # .doTrace cat("3rd line > tracingState(FALSE) ") [1] TRUE cat("4th linen") > f() } 1st line 1st 2nd line 2nd 2nd line 3rd line 4th line > # .doTrace > tracingState(TRUE) [1] FALSE
  • 42.
    trace trace f <- function(x) { > trace(f, edit = TRUE) # f cat("1st linen") Waiting for Emacs... if (TRUE) { [1] "f" cat("1st 2nd linen") > body(f) cat("2nd 2nd linen") { } cat("1st linen") cat("3rd linen") cat("3rd line browser() ") cat("4th linen") cat("4th linen") } } > f() 1st line 3rd line Called from: f() f <- function(x) { Browse[1]> cat("1st linen") cat("3rd linen") ※ .doTrace browser() cat("4th linen") tracingState }
  • 43.
    recover recover f<- function(x) { > f(1) x <- g(x) return(x) Enter a frame number, or 0 to exit } 1: f(1) g <- function(x) { 2: g(x) y <- x + 1 3: h(y) y <- h(y) return(y) Selection: 1 # f(1) } Called from: top level Browse[1]> x h <- function(y) { [1] 1 z <- y + 1 recover() return(z) }
  • 44.
    recover recover f<- function(x) { Browse[1]> c x <- g(x) return(x) Enter a frame number, or 0 to exit } 1: f(1) g <- function(x) { 2: g(x) y <- x + 1 3: h(y) y <- h(y) return(y) Selection: 2 # g(x) } Called from: f(1) Browse[1]> y h <- function(y) { [1] 2 z <- y + 1 recover() return(z) }
  • 45.
    recover recover f<- function(x) { Browse[1]> c x <- g(x) return(x) Enter a frame number, or 0 to exit } 1: f(1) g <- function(x) { 2: g(x) y <- x + 1 3: h(y) y <- h(y) return(y) Selection: 3 # h(y) } Called from: g(x) Browse[1]> z h <- function(y) { [1] 3 z <- y + 1 recover() return(z) }
  • 46.
    options(error = recover) recover recover f <- function(x) { > options(error = recover) x <- g(x) > f(1) return(x) Error in print(x) : object 'x' not } found g <- function(x) { Enter a frame number, or 0 to exit y <- x + 1 y <- h(y) 1: f(1) return(y) 2: g(x) } 3: h(y) 4: print(x) h <- function(y) { z <- y + 1 Selection: 3 # h(y) print(x) # Error! Called from: h(y) return(z) Browse[1]> x } Error during wrapup: object 'x' not found Browse[1]> ls() [1] "y" "z"
  • 47.
    options(error = dump.frames) dump.frames dump.frames recover f <- function(x) { > options(error = dump.frames) x <- g(x) > f(1) return(x) Error in print(x) : object 'x' not } found > ls() g <- function(x) { [1] "f" "g" "h" "last.dump" y <- x + 1 > debugger(last.dump) y <- h(y) Message: Error in print(x) : return(y) object 'x' not found } Available environments had calls: 1: f(1) h <- function(y) { 2: g(x) z <- y + 1 3: h(y) print(x) # Error! 4: print(x) return(z) } Enter an environment number, or 0 to exit Selection:
  • 48.
  • 49.
    ksvm > library(kernlab) > ksvm(Species~ ., + iris, + class.weights = c(versicolor = 1, setosa = 10), + prob.model = TRUE) Using automatic sigma estimation (sigest) for RBF or laplace kernel Error in lev(ret)[yd[cind]] : only 0's may be mixed with negative subscripts
  • 50.
    ksvm > options(error =recover) # recover > ksvm(Species ~ ., + iris, + class.weights = c(versicolor = 1, setosa = 10), + prob.model = TRUE) Using automatic sigma estimation (sigest) for RBF or laplace kernel Error in lev(ret)[yd[cind]] : only 0's may be mixed with negative subscripts Enter a frame number, or 0 to exit 1: ksvm(Species ~ ., iris, class.weights = c(versicolor = 1, setosa = 10), pro < > 9: .local(x, ...) 10: as.factor(lev(ret)[yd[cind]]) 11: is.factor(x) 12: inherits(x, "factor") Selection: 10
  • 51.
    ksvm Called from: toplevel Browse[1]> ls() [1] "x" Browse[1]> x Error during wrapup: promise already under evaluation: recursive default argument reference or earlier problems?
  • 52.
    ksvm Called from: toplevel Browse[1]> ls() [1] "x" Browse[1]> x Error during wrapup: promise already under evaluation: recursive default argument reference or earlier problems?
  • 53.
    ksvm > options(error =NULL) > ksvm(Species ~ ., + iris, + class.weights = c(versicolor = 1, setosa = 10), + prob.model = TRUE) Using automatic sigma estimation (sigest) for RBF or laplace kernel Error in lev(ret)[yd[cind]] : only 0's may be mixed with negative subscripts > ksvm # standardGeneric for "ksvm" defined from package "kernlab" function (x, ...) standardGeneric("ksvm") <environment: 0x103623e08> Methods may be defined for arguments: x Use showMethods("ksvm") for currently available ones. S4
  • 54.
    ksvm > showMethods("ksvm") Function: ksvm(package kernlab) x="formula" x="kernelMatrix" x="list" x="matrix" x="vector" > selectMethod(ksvm, "formula") Method Definition: function (x, ...) { .local <- function (x, data = NULL, ..., subset, na.action = na.omit, scaled = TRUE) < > ret <- ksvm(x, y, scaled = scaled, ...) < > signature matrix ksvm
  • 55.
    ksvm > selectMethod(ksvm, "matrix") MethodDefinition: function (x, ...) { .local <- function (x, y = NULL, scaled = TRUE, type = NULL, kernel = "rbfdot", kpar = "automatic", C = 1, nu = 0.2, < > , drop = FALSE][cind, ], as.factor(lev(ret) [yd[cind]]), < >
  • 56.
    ksvm > trace(ksvm, signature= “matrix”, edit = TRUE) browser browser() if (is.null(class.weights)) cret <- ksvm(x[c(indexes[[i]], indexes [[j]]), , drop = FALSE][cind, ], yd[cind], type = type(ret), kernel = kernel, kpar = NULL, C = C, nu = nu, tol = tol, scaled = FALSE, cross = 0, fit = FALSE, cache = cache, prob.model = FALSE) else cret <- ksvm(x[c(indexes[[i]], indexes [[j]]), , drop = FALSE][cind, ], as.factor(lev(ret) [yd[cind]]),
  • 57.
    ksvm > ksvm(Species ~., + iris, + class.weights = c(versicolor = 1, setosa = 10), + prob.model = TRUE) Using automatic sigma estimation (sigest) for RBF or laplace kernel Called from: .local(x, ...) Browse[1]> yd [1] -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 [22] -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 [43] -1 -1 -1 -1 -1 -1 -1 -1 1 1 1 1 1 1 1 1 1 1 1 1 1 [64] 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 [85] 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 lev(ret)[yd[cind]] yd (-1, 1) yd lev(ret)
  • 59.
    > 1:5 [1] 12 3 4 5 > .Last.value [1] 1 2 3 4 5 ESS TAB .Last.value
  • 60.
    f <- function(x){ y <- x g(y) } g <- function(x) { x <- x^2 browser() } > f(10) Called from: g(y) # x y Browse[1]> x # x 2 [1] 100 Browse[1]> y # y Error: object 'y' not found
  • 61.
    Browse[1]> evalq(y, parent.frame())# y [1] 10 Browse[1]> evalq(ls(), parent.frame()) # [1] "x" "y" Browse[1]> eval.parent(quote(y)) # part1 [1] 10 Browse[1]> get("y", parent.frame()) # part2 [1] 10 Browse[1]> ls(envir = parent.frame()) # [1] "x" "y" evalq(expr, parent.frame())
  • 62.
    apply browser f <- function() { a <- lapply(1:10000, function(x) { browser() # 1 browser() print(x) }) }
  • 63.
    apply browser > debug(f) > f() debugging in: f() debug: { a <- lapply(1:10000, function(x) { browser() print(x) }) } Browse[2]> n debug: a <- lapply(1:10000, function(x) { browser() print(x) }) Browse[2]> Called from: FUN(1:10000[[1L]], ...) Browse[2]> c [1] 1 Called from: FUN(1:10000[[2L]], ...) # browser() Browse[2]>
  • 64.
    apply browser Browse[2]> evalq(FUN <- edit(FUN), parent.frame()) function(x) { browser() # print(x) } Browse[2]> evalq(fix(FUN), parent.frame()) Browse[2]> FUN <<- evalq(edit(FUN), parent.frame())
  • 66.
  • 67.
    HI!! http://kohske.wordpress.com/?s=r+debug • An Introduction to the Interactive Debugging Tools in R http:// www.biostat.jhsph.edu/~rpeng/docs/R-debug-tools.pdf • Debugging in R http://www.stats.uwo.ca/faculty/murdoch/ software/debuggingR/ • Summer Computing 2011 Week 3:R debugging + misc http:// www.stat.cmu.edu/~hseltman/711/Week3.pdf • Rdebug http://www.math.ncu.edu.tw/~chenwc/R_note/ reference/debug/Rdebug.pdf