R: str(…) 与 getS3method(…,…)

me: 请教两个R的技术：1.R中有没有对象浏览器之类的工具？一举看完一个对象的子子孙孙 2.怎么看深入的源代码> ```prcomp function (x, ...) UseMethod("prcomp") <environment: namespace:stats>```

Yihui: 1. str()是很常用的一个函数，它可以充分查看对象的子子孙孙 2. 很多函数要么是S3 method，要么是调用C code，所以一般不能直接看源代码

S3 method可以用getS3method()去查看，比如prcomp就是S3方法，那么可以看它的default方法是什么：

`> getS3method('prcomp','default')`
```function (x, retx = TRUE, center = TRUE, scale. = FALSE, tol = NULL, ...) { x <- as.matrix(x) x <- scale(x, center = center, scale = scale.) cen <- attr(x, "scaled:center") sc <- attr(x, "scaled:scale") if (any(sc == 0)) stop("cannot rescale a constant/zero column to unit variance") s <- svd(x, nu = 0) s\$d <- s\$d/sqrt(max(1, nrow(x) - 1)) if (!is.null(tol)) { rank <- sum(s\$d > (s\$d[1L] * tol)) if (rank < ncol(x)) { s\$v <- s\$v[, 1L:rank, drop = FALSE] s\$d <- s\$d[1L:rank] } } dimnames(s\$v) <- list(colnames(x), paste("PC", seq_len(ncol(s\$v)), sep = "")) r <- list(sdev = s\$d, rotation = s\$v, center = if (is.null(cen)) FALSE else cen, scale = if (is.null(sc)) FALSE else sc) if (retx) r\$x <- x %*% s\$v class(r) <- "prcomp" r } <environment: namespace:stats>```

me: 多谢，节约俺好多搜索时间

Yihui: 嗯，我也是花了很长时间才明白S3 method的意思，呵呵

me: 如果要看biplot.prcomp呢？

Yihui: help会告诉你biplot也是generic function，可以应用在prcomp这种class上，所以：

```> getS3method('biplot','prcomp') function (x, choices = 1:2, scale = 1, pc.biplot = FALSE, ...) { if (length(choices) != 2) stop("length of choices must be 2") if (!length(scores <- x\$x)) stop(gettextf("object '%s' has no scores", deparse(substitute(x))), domain = NA) if (is.complex(scores)) stop("biplots are not defined for complex PCA") lam <- x\$sdev[choices] n <- NROW(scores) lam <- lam * sqrt(n) if (scale < 0 || scale > 1) warning("'scale' is outside [0, 1]") if (scale != 0) lam <- lam^scale else lam <- 1 if (pc.biplot) lam <- lam/sqrt(n) biplot.default(t(t(scores[, choices])/lam), t(t(x\$rotation[, choices]) * lam), ...) invisible() } <environment: namespace:stats>```