Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
R in Action, Second Edition.pdf
Скачиваний:
540
Добавлен:
26.03.2016
Размер:
20.33 Mб
Скачать

496

 

 

 

 

 

 

 

 

CHAPTER 21 Creating a package

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Multiple Comparisons

 

 

 

 

 

 

 

 

 

 

md=13

 

md=15.4

 

md=15.6

md=15.7

 

 

 

 

 

 

n=16

 

 

n=12

 

 

n=13

 

n=9

 

Age 65

17

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

15 16

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

(years) at

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Life Expectancy

13 14

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Healthy

12

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

South

 

North Central

 

 

West

Northeast

 

US Region

Figure 21.3 Annotated box plots displaying group differences. The plot is annotated with the medians and sample sizes for each group. The dotted vertical line represents the overall median.

family-wise error rate (the probability of finding one or more erroneous differences in a set of comparisons) at a reasonable level (say, .05).

The oneway() function accomplishes this by calling the p.adjust() function in the base R installation. The p.adjust() function adjusts p-values to account for multiple comparisons using one of several methods. The Bonferonni correction is perhaps the most well-known, but the Holm correction is more powerful and thus set as the default.

Differences among the groups are easiest to see with a graph. The plot() statement eproduces the side-by-side box plots in figure 21.3. The plot is annotated with a key that indicates the median and sample size for each group. A dotted horizontal line indicates the overall median for all observations combined.

It’s clear from these analyses that women in the South can expect fewer years of health past age 65. This has implications for the distribution and focus of health services. You might want to analyze the HLE estimates for males and see if you reach a similar conclusion.

The next section describes the code files for the npar package. You can download them (and save yourself some typing) from www.statmethods.net/RiA/nparFiles.zip.

21.2 Developing the package

The npar package consists of four functions: oneway(), print.oneway(), summary

.oneway(), and plot.oneway(). The first is the primary function that computes the statistics, and the others are S3 object-oriented generic functions (see section 20.3.1)

Developing the package

497

used to print and plot the results. Here, oneway indicates that there is a single grouping factor.

It’s a good idea to place each function in a separate text file with a .R extension. This isn’t strictly necessary, but it makes organizing the work easier. Additionally, it isn’t necessary for the names of the functions and the names of the files to match, but again, it’s good coding practice. The files are provided in listings 21.2 through 21.5.

Each file has a header consisting of a set of comments that start with the characters #'. The R interpreter ignores these lines, but you’ll use the roxygen2 package to turn the comments into your package documentation. These header comments will be discussed in section 21.3.

The oneway() function computes the statistics, and the print(), summary(), and plot() functions display the results. In the next section, you’ll develop the oneway() function.

21.2.1Computing the statistics

The oneway() function in the oneway.R text file performs all the statistical computations required.

Listing 21.2 Contents of the oneway.R file

#' @title Nonparametric group comparisons #'

#' @description

#' \code{oneway} computes nonparametric group comparisons, including an #' omnibus test and post-hoc pairwise group comparisons.

#'

#' @details

#' This function computes an omnibus Kruskal-Wallis test that the #' groups are equal, followed by all pairwise comparisons using

#' Wilcoxon Rank Sum tests. Exact Wilcoxon tests can be requested if #' there are no ties on the dependent variable. The p-values are

#' adjusted for multiple comparisons using the \code{\link{p.adjust}} #' function.

#'

#' @param formula an object of class formula, relating the dependent #' variable to the grouping variable.

#' @param data a data frame containing the variables in the model.

#' @param exact logical. If \code{TRUE}, calculate exact Wilcoxon tests. #' @param sort logical. If \code{TRUE}, sort groups by median dependent #' variable values.

#' @param method method for correcting p-values for multiple comparisons. #' @export

#' @return a list with 7 elements: #' \item{CALL}{function call}

#' \item{data}{data frame containing the depending and grouping variable} #' \item{sumstats}{data frame with descriptive statistics by group}

#' \item{kw}{results of the Kruskal-Wallis test} #' \item{method}{method used to adjust p-values}

#' \item{wmc}{data frame containing the multiple comparisons} #' \item{vnames}{variable names}

#' @author Rob Kabacoff <rkabacoff@@statmethods.net>

498

CHAPTER 21 Creating a package

 

 

 

 

 

#' @examples

 

 

 

 

 

 

#' results <- oneway(hlef ~ region, life)

 

 

 

 

 

 

#' summary(results)

 

 

 

 

 

 

#' plot(results, col="lightblue", main="Multiple Comparisons",

 

 

#'

xlab="US Region", ylab="Healthy Life Expectancy at Age 65")

 

 

oneway <- function(formula, data, exact=FALSE, sort=TRUE,

 

b Function

 

 

method=c("holm", "hochberg", "hommel", "bonferroni",

 

 

"BH", "BY", "fdr", "none")){

 

 

 

 

call

 

 

 

 

 

 

 

 

if (missing(formula) || class(formula) != "formula" ||

 

 

 

 

length(all.vars(formula)) != 2)

 

 

 

c Checks arguments

 

stop("'formula' is missing or incorrect")

 

 

 

 

 

 

 

 

 

method <- match.arg(method)

 

 

 

 

 

 

 

df <- model.frame(formula, data)

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

y <- df[[1]]

 

 

d Sets up data

 

 

 

 

 

 

g <- as.factor(df[[2]])

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

vnames <- names(df)

 

 

 

 

 

 

 

 

 

if(sort) g <- reorder(g, y, FUN=median)

 

 

 

 

 

 

 

groups <- levels(g)

 

 

 

 

 

e Reorders factor levels

 

k <- nlevels(g)

 

 

 

 

 

 

getstats <- function(x)(c(N = length(x), Median = median(x), MAD = mad(x)))

sumstats <- t(aggregate(y, by=list(g), FUN=getstats)[2]) rownames(sumstats) <- c("n", "median", "mad") colnames(sumstats) <- groups

kw <- kruskal.test(formula, data) wmc <- NULL

for (i in 1:(k-1)){ for (j in (i+1):k){

y1 <- y[g==groups[i]]

y2 <- y[g==groups[j]]

test <- wilcox.test(y1, y2, exact=exact)

r <- data.frame(Group.1=groups[i], Group.2=groups[j], W=test$statistic[[1]], p=test$p.value)

# note the [[]] to return a single number wmc <- rbind(wmc, r)

}

}

wmc$p <- p.adjust(wmc$p, method=method)

data <- data.frame(y, g) names(data) <- vnames

results <- list(CALL = match.call(), data=data, sumstats=sumstats, kw=kw,

method=method, wmc=wmc, vnames=vnames) class(results) <- c("oneway", "list")

return(results)

fSummary statistics

gStatistical tests

h Returns results

}

The header contains comments starting with #' that will be used by the roxygen2 package to create package documentation (see section 21.3). Next you see the

Developing the package

499

function argument list b. The user provides a formula of the form dependent variable~grouping variable and a data frame containing the data. By default, approximate p-values are computed, and the groups are ordered by their median dependent variable values. The user can choose from among eight adjustment methods, with the holm method (the first option in the list) chosen by default.

Once the user enters the arguments, they’re scanned for errors c. The if() function tests that the formula isn’t missing, that it’s a formula (variables ~ variables), and that there is only one variable on each side of the tilde (~). If any of these three conditions isn’t true, the stop() function halts execution, prints an error message, and returns the user to the R prompt. For debugging purposes, you can alter the error action with the options(error=) function. See section 20.5.3 for details.

The match.arg(arg, choices) function ensures that the user has entered an argument that matches one of the strings in the choices character vector. If a match isn’t found, an error is thrown, and, again, oneway() exits.

Next, the model.frame() function is used to create a data frame containing the dependent variable as the first column and the grouping variable as the second column d. In general, model.frame() returns a data frame containing all the variables in a formula. From this data frame, you create a numeric vector (y) containing the dependent variable and a factor vector (g) containing the grouping variable. The character vector vnames contains the variable names.

If sort=TRUE, you use the reorder() function to reorder the levels of the grouping variable g by the median dependent variable values y e. This is the default. The character vector groups contains the names of the groups, and the value k contains the number of groups.

Next, a numeric matrix (sumstats) is created, containing the sample size, median, and median absolute deviation for each group f. The aggregate() function uses the getstats() function to calculate the summary statistics, and the remaining code formats the table so that groups are columns and statistics are rows (I thought this was more attractive).

The statistical tests are then computed g. The results of the Kruskal–Wallis test are saved to a list called kw. The for() functions calculate every pairwise Wilcoxon test. The results of these pairwise tests are saved in the wmc data frame:

 

Group.1

Group.2

W

p

1

South North Central 28.0 0.008583

2

South

West 27.0 0.004738

3

South

Northeast 17.0 0.008583

4

North Central

West 63.5

1.000000

5

North Central

Northeast 42.0

1.000000

6

West

Northeast 54.5

1.000000

Here, Group.1 and Group.2 indicate the groups being compared to each other, W is the Wilcoxon statistic, and p is the (adjusted) p-value for each comparison.

Finally, the results are bundled up and returned as a list h. The list contains seven components, which are summarized in table 21.1. Additionally, you set the class of the

Соседние файлы в предмете [НЕСОРТИРОВАННОЕ]