content
stringlengths 0
14.9M
| filename
stringlengths 44
136
|
---|---|
# Xpose 4
# An R-based population pharmacokinetic/
# pharmacodynamic model building aid for NONMEM.
# Copyright (C) 1998-2004 E. Niclas Jonsson and Mats Karlsson.
# Copyright (C) 2005-2008 Andrew C. Hooker, Justin J. Wilkins,
# Mats O. Karlsson and E. Niclas Jonsson.
# Copyright (C) 2009-2010 Andrew C. Hooker, Mats O. Karlsson and
# E. Niclas Jonsson.
# This file is a part of Xpose 4.
# Xpose 4 is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public License
# as published by the Free Software Foundation, either version 3
# of the License, or (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
# You should have received a copy of the GNU Lesser General Public License
# along with this program. A copy can be cound in the R installation
# directory under \share\licenses. If not, see http://www.gnu.org/licenses/.
#' @describeIn add_transformed_columns Create a time-after-dose
#' (TAD) data item based upon the dose and time variables in the dataset.
#' @export
"add.tad"<-
#function(runno = get(fr = 0, "runno"))
function(object, classic=FALSE)
{
tab.suffix <- ""
ans <- ""
idv.nam <- object@Prefs@Xvardef$idv
if(is.null(idv.nam)) {
cat("The IDV wasn't set in the current database.\n")
cat("Please type the name of the independent variable to use in\n")
cat("calculations, or press return for the default table file column\n")
cat("(sdtab and mytab column 2, mutab column 3): ")
ans <- readline()
}
"make.tad" <- function(indat, idvcol) {
tad <- rep(0, length.out = nrow(indat))
for(i in 1:nrow(indat)) {
if(indat$WRES[i] == 0) {
last.dose <- indat[[idvcol]][i]
} else {
tad[i] <- indat[[idvcol]][i] - last.dose
}
}
return(tad)
}
dat <- object@Data
sdat <- object@SData
dat$TAD <- make.tad(dat, match(xvardef("idv", object), names(dat)))
if(!is.null(sdat))
sdat$TAD <- make.tad(sdat, match(xvardef("idv", object), names(sdat)))
object@Data <- dat
if(!is.null(sdat))
object@SData <- sdat
data <- object
data@Prefs@Labels$TAD <- c("Time after dose (h)")
#assign(object, data, immediate=T, env = .GlobalEnv)
if (classic==TRUE) {
#assign(paste("xpdb", object@Runno, sep = ""), data, immediate=T, envir = .GlobalEnv)
#assign(pos = 1, ".cur.db", eval(as.name(paste("xpdb", object@Runno, sep = ""))))
#return(cat(""))
## to avoid checks on global variable assignment in package building
c1<-call("assign",paste("xpdb", object@Runno, sep = ""),object,envir=.GlobalEnv)
eval(c1)
c2<-call("assign",pos = 1, ".cur.db", eval(as.name(paste("xpdb", object@Runno, sep = ""))))
eval(c2)
return(cat(""))
} else {
return(data)
}
}
| /scratch/gouwar.j/cran-all/cranData/xpose4/R/add.tad.R |
#' Generic internal functions for Xpose 4
#'
#' These are internal functions relating to the Xpose generic functions.
#'
#' These are internal Xpose functions, for adding ID numbers, computing
#' prediction intervals, randomization, stacking, and binning. They are not
#' intended for direct use.
#'
#'
#'
#' @return Internal helper functions for the generic Xpose functions.
#' @author Justin Wilkins and Andrew Hooker
#' @keywords internal
#' @importFrom stats residuals
#' @importFrom stats loess
addid <- function(x,y,
ids = ids,
idsmode=NULL,
idsext =0.05,
idscex= 0.7,
idsdir= "both",
gridmode=TRUE
) {
textfun <- "text"
if(gridmode) textfun <- "ltext"
if(!is.null(idsmode)) {
do.call(textfun,list(x,y,ids,cex=idscex))
} else {
idd <- ids
yres <- residuals(loess(y~x))
xcut <- cut(x,breaks=4,include.lowest=TRUE)
## Determine the number of points to plot
if(idsext < 1) { # Fraction of total number of points
idsext <- ceiling(length(x)*idsext/4)
}
for(pp in levels(xcut)) {
sel <- xcut == pp
yyres <- yres[sel]
xx <- x[sel]
yy <- y[sel]
iidd <- idd[sel]
ord <- order(yyres)
ordy <- yy[ord]
ordx <- xx[ord]
ordidd <- iidd[ord]
if(!is.null(idsdir)) {
## Lower extreme
if(idsdir=="both" || idsdir=="down") {
do.call(textfun,list(ordx[1:idsext],
ordy[1:idsext],
ordidd[1:idsext],
cex=idscex))
}
## Upper extreme
if(idsdir=="both" || idsdir=="up") {
ll <- length(ordx)
## Sanity check on ll added by Justin 10/10/05
## to prevent subscript errors in conditioned plots
if (ll!=0) {
try(
do.call(textfun,list(ordx[(ll-idsext+1):ll],
ordy[(ll-idsext+1):ll],
ordidd[(ll-idsext+1):ll],
cex=idscex)), silent=T)
}
}
}
}
}
}
| /scratch/gouwar.j/cran-all/cranData/xpose4/R/addid.R |
#' Additional goodness-of-fit plots, for Xpose 4
#'
#' This is a compound plot consisting of plots of weighted population residuals
#' (WRES) vs population predictions (PRED), absolute individual weighted
#' residuals (|IWRES|) vs independent variable (IDV), WRES vs IDV, and weighted
#' population residuals vs log(IDV), a specific function in Xpose 4. It is a
#' wrapper encapsulating arguments to the \code{wres.vs.pred},
#' \code{iwres.vs.idv} and \code{wres.vs.idv} functions.
#'
#' Four additional goodness-of-fit plots are presented side by side for
#' comparison.
#'
#' A wide array of extra options controlling xyplots are available. See
#' \code{\link{xpose.plot.default}} and
#' \code{\link{xpose.multiple.plot.default}} for details.
#'
#' @param object An xpose.data object.
#' @param type 1-character string giving the type of plot desired. The
#' following values are possible, for details, see 'plot': '"p"' for points,
#' '"l"' for lines, '"o"' for over-plotted points and lines, '"b"', '"c"') for
#' (empty if '"c"') points joined by lines, '"s"' and '"S"' for stair steps and
#' '"h"' for histogram-like vertical lines. Finally, '"n"' does not produce
#' any points or lines.
#' @param title.size Amount, in a range of 0-1, of how much space the title
#' should take up in the plot)
#' @param title.just how the title should be justified
#' @param main The title of the plot. If \code{"Default"} then a default title
#' is plotted. Otherwise the value should be a string like \code{"my title"} or
#' \code{NULL} for no plot title.
#' @param force.wres Plot the WRES even if other residuals are available.
#' @param \dots Other arguments passed to \code{link{xpose.plot.default}}.
#' @return Returns a compound plot comprising plots of weighted population
#' residuals (WRES) vs population predictions (PRED), absolute individual
#' weighted residuals (|IWRES|) vs independent variable (IDV), WRES vs IDV, and
#' weighted population residuals vs log(IDV).
#' @author E. Niclas Jonsson, Mats Karlsson, Andrew Hooker & Justin Wilkins
#' @seealso \code{\link{wres.vs.pred}}, \code{\link{iwres.vs.idv}},
#' \code{\link{wres.vs.idv}}, \code{\link{xpose.plot.default}},
#' \code{\link{xpose.panel.default}}, \code{\link[lattice]{xyplot}},
#' \code{\link{xpose.prefs-class}}, \code{\link{xpose.data-class}}
#' @keywords methods
#' @examples
#' ## Here we load the example xpose database
#' xpdb <- simpraz.xpdb
#'
#' ## A vanilla plot
#' addit.gof(xpdb)
#'
#' @export addit.gof
#' @family specific functions
"addit.gof" <-
function(object,
type="p",
title.size=0.02,
title.just=c("center","top"),
main="Default",
force.wres=FALSE,
...) {
if(is.null(check.vars(c("dv","pred","ipred","iwres","idv"),
object,silent=FALSE))) {
return()
}
use.cwres=TRUE
if(force.wres){
use.cwres=FALSE
if(is.null(check.vars(c("wres"),object,silent=FALSE))) return()
} else {
if(is.null(check.vars(c("cwres"),object,silent=TRUE))) {
use.cwres=FALSE
if(is.null(check.vars(c("wres"),object,silent=FALSE))) return()
}
}
## create empty list for plots
num.of.plots <- 4
plotList <- vector("list",length(num.of.plots))
if(use.cwres){
xplot1 <- cwres.vs.pred(object,
main=NULL,
type=type,
pass.plot.list=TRUE,
...)
xplot3 <- cwres.vs.idv(object,
main=NULL,
type="n",
ids=F,
pass.plot.list=TRUE,
...)
xplot4 <- cwres.vs.idv(object,
main=NULL,
logx=T,
type=type,
pass.plot.list=TRUE,
...)
} else {
xplot1 <- wres.vs.pred(object,
main=NULL,
type=type,
pass.plot.list=TRUE,
...)
xplot3 <- wres.vs.idv(object,
main=NULL,
type="n",
ids=F,
pass.plot.list=TRUE,
...)
xplot4 <- wres.vs.idv(object,
main=NULL,
logx=T,
type=type,
pass.plot.list=TRUE,
...)
}
xplot2 <- absval.iwres.vs.idv(object,
main=NULL,
ylb=paste("Absolute value of iWRES"),
pass.plot.list=TRUE,
...)
plotList[[1]] <- xplot1
plotList[[2]] <- xplot2
plotList[[3]] <- xplot3
plotList[[4]] <- xplot4
default.plot.title <- "Additional goodness of fit plots"
plotTitle <- xpose.multiple.plot.title(object=object,
plot.text = default.plot.title,main=main,
...)
obj <- xpose.multiple.plot(plotList,plotTitle,...)
return(obj)
}
| /scratch/gouwar.j/cran-all/cranData/xpose4/R/addit.gof.R |
# Xpose 4
# An R-based population pharmacokinetic/
# pharmacodynamic model building aid for NONMEM.
# Copyright (C) 1998-2004 E. Niclas Jonsson and Mats Karlsson.
# Copyright (C) 2005-2008 Andrew C. Hooker, Justin J. Wilkins,
# Mats O. Karlsson and E. Niclas Jonsson.
# Copyright (C) 2009-2010 Andrew C. Hooker, Mats O. Karlsson and
# E. Niclas Jonsson.
# This file is a part of Xpose 4.
# Xpose 4 is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public License
# as published by the Free Software Foundation, either version 3
# of the License, or (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
# You should have received a copy of the GNU Lesser General Public License
# along with this program. A copy can be cound in the R installation
# directory under \share\licenses. If not, see http://www.gnu.org/licenses/.
another.menu <- function() {
choices <- c(
"List letters",
"Covariate model ->",
"Quit"
)
pick <- menu(choices,title="Another menu")
#cat(pick,"\n")
qx <- 0
switch(pick + 1,
qx <- 1,
cat(letters,"\n"),
##wres.vs.cov(xpdb5),
##wres.vs.cov(.cur.db),
qx <- covariate.model.menu(),
qx <- 1
)
#cat(qx,"\n")
if(qx == 1) {
## Turn of graphics window
if(dev.cur() > 1){
dev.off()
}
return(invisible(1))
} else {
Recall()
}
}
| /scratch/gouwar.j/cran-all/cranData/xpose4/R/another.menu.R |
# Xpose 4
# An R-based population pharmacokinetic/
# pharmacodynamic model building aid for NONMEM.
# Copyright (C) 1998-2004 E. Niclas Jonsson and Mats Karlsson.
# Copyright (C) 2005-2008 Andrew C. Hooker, Justin J. Wilkins,
# Mats O. Karlsson and E. Niclas Jonsson.
# Copyright (C) 2009-2010 Andrew C. Hooker, Mats O. Karlsson and
# E. Niclas Jonsson.
# This file is a part of Xpose 4.
# Xpose 4 is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public License
# as published by the Free Software Foundation, either version 3
# of the License, or (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
# You should have received a copy of the GNU Lesser General Public License
# along with this program. A copy can be cound in the R installation
# directory under \share\licenses. If not, see http://www.gnu.org/licenses/.
#' Autocorrelation of conditional weighted residuals for Xpose 4
#'
#' This is an autocorrelation plot of conditional weighted residuals, a
#' specific function in Xpose 4. Most of the options take their default values
#' from xpose.data object but may be overridden by supplying them as arguments.
#'
#' A wide array of extra options controlling xyplots are available. See
#' \code{\link{xpose.plot.default}} for details.
#'
#' Conditional weighted residuals (CWRES) require some extra steps to
#' calculate. See \code{\link{compute.cwres}} for details.
#'
#' @param object An xpose.data object.
#' @param smooth Logical value indicating whether a smooth should be
#' superimposed.
#' @param type 1-character string giving the type of plot desired. The
#' following values are possible, for details, see \code{\link{plot}}: '"p"'
#' for points, '"l"' for lines, '"o"' for over-plotted points and lines, '"b"',
#' '"c"') for (empty if '"c"') points joined by lines, '"s"' and '"S"' for
#' stair steps and '"h"' for histogram-like vertical lines. Finally, '"n"'
#' does not produce any points or lines.
#' @param ids A logical value indicating whether text labels should be used as
#' plotting symbols (the variable used for these symbols indicated by the
#' \code{idlab} xpose data variable).
#' @param main The title of the plot. If \code{"Default"} then a default title
#' is plotted. Otherwise the value should be a string like \code{"my title"} or
#' \code{NULL} for no plot title.
#' @param \dots Other arguments passed to \code{link{xpose.plot.default}}.
#' @return Returns an autocorrelation plot for conditional weighted population
#' residuals (CWRES).
#' @author E. Niclas Jonsson, Mats Karlsson, Andrew Hooker & Justin Wilkins
#' @seealso \code{\link[lattice]{xyplot}}, \code{\link{xpose.prefs-class}},
#' \code{\link{compute.cwres}}, \code{\link{xpose.data-class}}
#' @keywords methods
#' @examples
#'
#' \dontrun{
#' ## We expect to find the required NONMEM run and table files for run
#' ## 5 in the current working directory
#' xpdb5 <- xpose.data(5)
#' }
#'
#' ## Here we load the example xpose database
#' data(simpraz.xpdb)
#' xpdb <- simpraz.xpdb
#'
#' ## A vanilla plot
#' autocorr.cwres(xpdb)
#'
#' ## A conditioning plot
#' autocorr.cwres(xpdb, dilution=TRUE)
#'
#' ## Custom heading and axis labels
#' autocorr.cwres(xpdb, main="My conditioning plot", ylb="|CWRES|", xlb="PRED")
#'
#' ## Custom colours and symbols, IDs
#' autocorr.cwres(xpdb, cex=0.6, pch=3, col=1, ids=TRUE)
#'
#'
#' @export autocorr.cwres
#' @family specific functions
"autocorr.cwres" <-
function(object,
#ylb = "|WRES|",
#idsdir="up",
type="p",
smooth=TRUE,
ids=F,
main = "Default",
...) {
if(is.null(check.vars(c("cwres"),
object,silent=FALSE))) {
return()
}
default.plot.title <- paste("Autocorrelation of ",xlabel(xvardef("cwres",object),object),
sep="")
plotTitle <- xpose.multiple.plot.title(object=object,
plot.text = default.plot.title,
main=main,
...)
xplot <- xpose.plot.default(xvardef("cwres",object),
xvardef("cwres",object),
object,
#ylb=ylb,
#idsdir=idsdir,
type=type,
smooth=smooth,
ids=ids,
autocorr=TRUE,
main=plotTitle,
...)
return(xplot)
}
| /scratch/gouwar.j/cran-all/cranData/xpose4/R/autocorr.cwres.R |
#' autocorrelation of the individual weighted residuals
#'
#'
#' @inheritParams xpose.plot.default
#' @inheritParams xpose.panel.default
#' @return A Lattice object
#' @export
#'
#'
#' @family specific functions
autocorr.iwres <-
function(object,
#ylb = "|WRES|",
#idsdir="up",
type="p",
smooth=TRUE,
ids=F,
main = "Default",
...) {
if(is.null(check.vars(c("iwres"),
object,silent=FALSE))) {
return()
}
default.plot.title <- paste("Autocorrelation of ",xlabel(xvardef("iwres",object),object),
sep="")
plotTitle <- xpose.multiple.plot.title(object=object,
plot.text = default.plot.title,
main=main,
...)
xplot <- xpose.plot.default(xvardef("iwres",object),
xvardef("iwres",object),
object,
#ylb=ylb,
#idsdir=idsdir,
type=type,
smooth=smooth,
ids=ids,
autocorr=TRUE,
main=plotTitle,
...)
return(xplot)
}
| /scratch/gouwar.j/cran-all/cranData/xpose4/R/autocorr.iwres.R |
# Xpose 4
# An R-based population pharmacokinetic/
# pharmacodynamic model building aid for NONMEM.
# Copyright (C) 1998-2004 E. Niclas Jonsson and Mats Karlsson.
# Copyright (C) 2005-2008 Andrew C. Hooker, Justin J. Wilkins,
# Mats O. Karlsson and E. Niclas Jonsson.
# Copyright (C) 2009-2010 Andrew C. Hooker, Mats O. Karlsson and
# E. Niclas Jonsson.
# This file is a part of Xpose 4.
# Xpose 4 is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public License
# as published by the Free Software Foundation, either version 3
# of the License, or (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
# You should have received a copy of the GNU Lesser General Public License
# along with this program. A copy can be cound in the R installation
# directory under \share\licenses. If not, see http://www.gnu.org/licenses/.
## Added by Justin Wilkins 6 Dec 2005
## BUG: mirror=3 repeats the same simulated plot 3 times
## with warning "longer object length is not a multiple of shorter object length in: data$iter == samp"
## Traced to SData.R, line 9
#' Autocorrelation of weighted residuals for Xpose 4
#'
#' This is an autocorrelation plot of weighted residuals. Most of the options
#' take their default values from the xpose.data object but may be overridden
#' by supplying them as arguments.
#'
#' A wide array of extra options controlling xyplots are available. See
#' \code{\link{xpose.plot.default}} for details.
#'
#' @param object An xpose.data object.
#' @param smooth Logical value indicating whether a smooth should be
#' superimposed.
#' @param type 1-character string giving the type of plot desired. The
#' following values are possible, for details, see \code{\link{plot}}: '"p"'
#' for points, '"l"' for lines, '"o"' for over-plotted points and lines, '"b"',
#' '"c"') for (empty if '"c"') points joined by lines, '"s"' and '"S"' for
#' stair steps and '"h"' for histogram-like vertical lines. Finally, '"n"'
#' does not produce any points or lines.
#' @param ids A logical value indicating whether text labels should be used as
#' plotting symbols (the variable used for these symbols indicated by the
#' \code{idlab} xpose data variable).
#' @param main The title of the plot. If \code{"Default"} then a default title
#' is plotted. Otherwise the value should be a string like \code{"my title"} or
#' \code{NULL} for no plot title.
#' @param \dots Other arguments passed to \code{link{xpose.plot.default}}.
#' @return Returns an autocorrelation plot for weighted population residuals
#' (WRES) or individual weighted residuals (IWRES).
#' @author E. Niclas Jonsson, Mats Karlsson, Justin Wilkins & Andrew Hooker
#' @seealso \code{\link[lattice]{xyplot}}, \code{\link{xpose.prefs-class}},
#' \code{\link{xpose.data-class}}
#' @keywords methods
#' @examples
#'
#' \dontrun{
#' ## We expect to find the required NONMEM run and table files for run
#' ## 5 in the current working directory
#' xpdb5 <- xpose.data(5)
#' }
#'
#' ## Here we load the example xpose database
#' data(simpraz.xpdb)
#' xpdb <- simpraz.xpdb
#'
#' ## A vanilla plot
#' autocorr.wres(xpdb)
#'
#' ## A conditioning plot
#' autocorr.wres(xpdb, dilution=TRUE)
#'
#' ## Custom heading and axis labels
#' autocorr.wres(xpdb, main="My conditioning plot", ylb="|CWRES|", xlb="PRED")
#'
#' ## Custom colours and symbols, IDs
#' autocorr.wres(xpdb, cex=0.6, pch=3, col=1, ids=TRUE)
#'
#' ## A vanilla plot with IWRES
#' autocorr.iwres(xpdb)
#'
#' @export autocorr.wres
#' @family specific functions
"autocorr.wres" <-
function(object,
#ylb = "|WRES|",
#idsdir="up",
type="p",
smooth=TRUE,
ids=F,
main = "Default",
...) {
if(is.null(check.vars(c("wres"),
object,silent=FALSE))) {
return()
}
default.plot.title <- paste("Autocorrelation of ",xlabel(xvardef("wres",object),object),
sep="")
plotTitle <- xpose.multiple.plot.title(object=object,
plot.text = default.plot.title,
main=main,
...)
xplot <- xpose.plot.default(xvardef("wres",object),
xvardef("wres",object),
object,
#ylb=ylb,
#idsdir=idsdir,
type=type,
smooth=smooth,
ids=ids,
autocorr=TRUE,
main=plotTitle,
...)
return(xplot)
}
| /scratch/gouwar.j/cran-all/cranData/xpose4/R/autocorr.wres.R |
#' Basic goodness-of-fit plots, for Xpose 4
#'
#' This is a compound plot consisting of plots of observations (DV) vs
#' population predictions (PRED), observations (DV) vs individual predictions
#' (IPRED), absolute individual weighted residuals (|IWRES|) vs IPRED, and
#' weighted population residuals (CWRES) vs independent variable (IDV), a
#' specific function in Xpose 4. WRES are also supported. It is a wrapper
#' encapsulating arguments to the \code{dv.vs.pred}, \code{dv.vs.ipred},
#' \code{absval.iwres.vs.ipred} and \code{wres.vs.idv} functions.
#'
#' Four basic goodness-of-fit plots are presented side by side for comparison.
#'
#' Conditional weighted residuals (CWRES) require some extra steps to
#' calculate. See \code{\link{compute.cwres}} for details.
#'
#' A wide array of extra options controlling xyplots are available. See
#' \code{\link{xpose.plot.default}} for details.
#'
#' \code{basic.gof.cwres} is just a wrapper for \code{basic.gof} with
#' \code{use.cwres=TRUE}.
#'
#' @param object An xpose.data object.
#' @param force.wres Should the plots use WRES? Values can be
#' \code{TRUE/FALSE}. Otherwise the CWRES are used if present.
#' @param main The title of the plot. If \code{"Default"} then a default title
#' is plotted. Otherwise the value should be a string like \code{"my title"} or
#' \code{NULL} for no plot title.
#' @param use.log Should we use log transformations in the plots?
#' @param \dots Other arguments passed to \code{\link{xpose.plot.default}}.
#' @return Returns a compound plot comprising plots of observations (DV) vs
#' population predictions (PRED), DV vs individual predictions (IPRED),
#' absolute individual weighted residuals (|IWRES|) vs IPRED, and weighted
#' populations residuals (WRES) vs the independent variable (IDV).
#' @author E. Niclas Jonsson, Mats Karlsson, Andrew Hooker & Justin Wilkins
#' @seealso \code{\link{dv.vs.pred}}, \code{\link{dv.vs.ipred}},
#' \code{\link{absval.iwres.vs.ipred}}, \code{\link{wres.vs.idv}},
#' \code{\link{cwres.vs.idv}}, \code{\link{xpose.plot.default}},
#' \code{\link{xpose.panel.default}}, \code{\link[lattice]{xyplot}},
#' \code{\link{compute.cwres}}, \code{\link{xpose.prefs-class}},
#' \code{\link{xpose.data-class}}
#' @examples
#'
#' basic.gof(simpraz.xpdb)
#'
#' @export basic.gof
#' @family specific functions
basic.gof <-
function(object,
force.wres=FALSE,
main="Default",
use.log = FALSE,
...) {
if(is.null(check.vars(c("dv","pred","ipred","iwres","idv"),
object,silent=FALSE))) {
return()
}
use.cwres=TRUE
if(force.wres){
use.cwres=FALSE
if(is.null(check.vars(c("wres"),object,silent=FALSE))) return()
} else {
if(is.null(check.vars(c("cwres"),object,silent=TRUE))) {
use.cwres=FALSE
if(is.null(check.vars(c("wres"),object,silent=FALSE))) return()
}
}
## create enpty list for plots
num.of.plots <- 4
plotList <- vector("list",num.of.plots)
loglist <- c(dv=F, pred=F, ipred=F, iwres=F, wres=F, idv=F,cwres=F)
if(use.log){
loglist['dv']<-T
loglist['pred']<-T
loglist['ipred']<-T
}
xplot1 <- dv.vs.pred(object,
main=NULL,
pass.plot.list=TRUE,
logx=loglist['pred'], logy=loglist['dv'],
...)
xplot2 <- dv.vs.ipred(object,
main=NULL,
pass.plot.list=TRUE,
logx=loglist['ipred'], logy=loglist['dv'],
...)
xplot3 <- absval.iwres.vs.ipred(object,
main=NULL,
#ids=FALSE,
pass.plot.list=TRUE,
logx=loglist['ipred'], logy=loglist['iwres'],
...)
if(use.cwres){
xplot4 <- cwres.vs.idv(object,
main=NULL,
pass.plot.list=TRUE,
logx=loglist['idv'], logy=loglist['cwres'],
...)
} else {
xplot4 <- wres.vs.idv(object,
main=NULL,
pass.plot.list=TRUE,
logx=loglist['idv'], logy=loglist['wres'],
...)
}
plotList[[1]] <- xplot1
plotList[[2]] <- xplot2
plotList[[3]] <- xplot3
plotList[[4]] <- xplot4
default.plot.title <- "Basic goodness-of-fit plots"
plotTitle <- xpose.multiple.plot.title(object=object,
plot.text = default.plot.title,
main=main,
...)
obj <- xpose.multiple.plot(plotList,plotTitle,...)
return(obj)
}
| /scratch/gouwar.j/cran-all/cranData/xpose4/R/basic.gof.R |
# Xpose 4
# An R-based population pharmacokinetic/
# pharmacodynamic model building aid for NONMEM.
# Copyright (C) 1998-2004 E. Niclas Jonsson and Mats Karlsson.
# Copyright (C) 2005-2008 Andrew C. Hooker, Justin J. Wilkins,
# Mats O. Karlsson and E. Niclas Jonsson.
# Copyright (C) 2009-2010 Andrew C. Hooker, Mats O. Karlsson and
# E. Niclas Jonsson.
# This file is a part of Xpose 4.
# Xpose 4 is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public License
# as published by the Free Software Foundation, either version 3
# of the License, or (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
# You should have received a copy of the GNU Lesser General Public License
# along with this program. A copy can be cound in the R installation
# directory under \share\licenses. If not, see http://www.gnu.org/licenses/.
#' Basic model comparison plots, for Xpose 4
#'
#' This creates a stack of four plots, comparing PRED, IPRED, WRES (or CWRES),
#' and IWRES estimates for the two specified model fits.
#'
#' Four basic model comparison plots are displayed in sequence.
#'
#' Conditional weighted residuals (CWRES) require some extra steps to
#' calculate. See \code{\link{compute.cwres}} for details.
#'
#' A wide array of extra options controlling xyplots are available. See
#' \code{\link{xpose.plot.default}} for details.
#'
#' @param object An xpose.data object.
#' @param object.ref An xpose.data object. If not supplied, the user will be
#' prompted.
#' @param inclZeroWRES Logical value indicating whether rows with WRES=0 is
#' included in the plot. The default is TRUE.
#' @param onlyfirst Logical value indicating whether only the first row per
#' individual is included in the plot.
#' @param subset A string giving the subset expression to be applied to the
#' data before plotting. See \code{\link{xsubset}}.
#' @param main The title of the plot. If \code{"Default"} then a default title
#' is plotted. Otherwise the value should be a string like \code{"my title"} or
#' \code{NULL} for no plot title.
#' @param force.wres Force function to use WRES?
#' @param \dots Other arguments passed to \code{link{xpose.plot.default}}.
#' @return Returns a stack of plots comprising comparisons of PRED, IPRED, WRES
#' (or CWRES) and IWRES for the two specified runs.
#' @author E. Niclas Jonsson, Mats Karlsson, Andrew Hooker & Justin Wilkins
#' @seealso \code{\link{xpose.plot.default}},
#' \code{\link{xpose.panel.default}}, \code{\link[lattice]{xyplot}},
#' \code{\link{compute.cwres}}, \code{\link{xpose.prefs-class}},
#' \code{\link{xpose.data-class}}
#' @keywords methods
#' @examples
#'
#' \dontrun{
#' ## We expect to find the required NONMEM run and table files for runs
#' ## 5 and 6 in the current working directory
#' xpdb5 <- xpose.data(5)
#' xpdb6 <- xpose.data(6)
#'
#' ## A vanilla plot, without prompts
#' basic.model.comp(xpdb5, xpdb6, prompt = FALSE)
#'
#' ## Custom colours and symbols, no user IDs
#' basic.model.comp.cwres(xpdb5, xpdb6, cex=0.6, pch=8, col=1, ids=NULL)
#' }
#'
#'
#' @export basic.model.comp
#' @family specific functions
"basic.model.comp" <- function(object,
object.ref = NULL,
onlyfirst = FALSE,
inclZeroWRES = FALSE,
subset = xsubset(object),
#prompt = TRUE,
main="Default",
force.wres=FALSE,
#ref.default = ".ref.db",
...) {
if (is.null(object.ref)) {
ref.list <- get.refrunno()
if(exists(".ref.db")){
object.ref <- eval(parse(text=".ref.db"))
} else {
return()
}
if(any(is.null(ref.list)))
return()
}
if(dim(object@Data)[1] != dim(object.ref@Data)[1]) {
cat("The current database and the reference database do not have\n")
cat("the same number of lines!\n")
invisible()
return()
}
if(is.null(check.vars(c("idlab","pred","ipred","iwres"),
object,silent=FALSE))) {
return()
}
use.cwres=TRUE
if(force.wres){
use.cwres=FALSE
if(is.null(check.vars(c("wres"),object,silent=FALSE))) return()
} else {
if(is.null(check.vars(c("cwres"),object,silent=TRUE))) {
use.cwres=FALSE
if(is.null(check.vars(c("wres"),object,silent=FALSE))) return()
}
}
object@Data$PRED.REF <- object.ref@Data[,xvardef("pred", object.ref)]
object@Data$IPRED.REF <- object.ref@Data[,xvardef("ipred", object.ref)]
if(use.cwres){
object@Data$CWRES.REF <- object.ref@Data[,xvardef("cwres", object.ref)]
} else {
object@Data$WRES.REF <- object.ref@Data[,xvardef("wres", object.ref)]
}
object@Data$IWRES.REF <- object.ref@Data[,xvardef("iwres", object.ref)]
## PRED vs PRED
if(!any(is.null(xvardef("pred", object))) && !any(is.null(xvardef("pred", object.ref)))) {
xlb <- paste(xlabel(xvardef("pred",object),object), " (Run ", object@Runno, ")",sep="")
ylb <- paste(xlabel(xvardef("pred",object.ref),object.ref), " (Run ", object.ref@Runno, ")",sep="")
main <- paste(ylb, " vs ", xlb, sep="")
xplot1 <- xpose.plot.default(xvardef("pred", object),
"PRED.REF",
object,
xlb = xlb,
ylb = ylb,
main = NULL,
abline=c(0,1),
onlyfirst = onlyfirst,
inclZeroWRES = inclZeroWRES,
subset = subset,
...)
}
# IPRED vs IPRED
if(!any(is.null(xvardef("ipred", object))) && !any(is.null(xvardef("ipred", object.ref)))) {
xlb <- paste(xlabel(xvardef("ipred",object),object), " (Run ", object@Runno, ")",sep="")
ylb <- paste(xlabel(xvardef("ipred",object.ref),object.ref), " (Run ", object.ref@Runno, ")",sep="")
main <- paste(ylb, " vs ", xlb, sep="")
xplot2 <- xpose.plot.default(xvardef("ipred", object),
"IPRED.REF",
object,
xlb = xlb,
ylb = ylb,
main = NULL,
abline=c(0,1),
onlyfirst = onlyfirst,
inclZeroWRES = inclZeroWRES,
subset = subset,
...)
}
if(use.cwres){
## CWRES vs CWRES
if(!any(is.null(xvardef("cwres", object))) && !any(is.null(xvardef("cwres", object.ref)))) {
xlb <- paste(xlabel(xvardef("cwres",object),object), " (Run ", object@Runno, ")",sep="")
ylb <- paste(xlabel(xvardef("cwres",object.ref),object.ref), " (Run ", object.ref@Runno, ")",sep="")
main <- paste(ylb, " vs ", xlb, sep="")
xplot3 <- xpose.plot.default(xvardef("cwres", object),
"CWRES.REF",
object,
xlb = xlb,
ylb = ylb,
main = NULL,
abline=c(0,1),
onlyfirst = onlyfirst,
inclZeroWRES = inclZeroWRES,
subset = subset,
...)
}
} else {
## WRES vs WRES
if(!any(is.null(xvardef("wres", object))) && !any(is.null(xvardef("wres", object.ref)))) {
xlb <- paste(xlabel(xvardef("wres",object),object), " (Run ", object@Runno, ")",sep="")
ylb <- paste(xlabel(xvardef("wres",object.ref),object.ref), " (Run ", object.ref@Runno, ")",sep="")
main <- paste(ylb, " vs ", xlb, sep="")
xplot3 <- xpose.plot.default(xvardef("wres", object),
"WRES.REF",
object,
xlb = xlb,
ylb = ylb,
main = NULL,
abline=c(0,1),
onlyfirst = onlyfirst,
inclZeroWRES = inclZeroWRES,
subset = subset,
...)
}
}
# IWRES vs IWRES
if(!any(is.null(xvardef("iwres", object))) && !any(is.null(xvardef("iwres", object.ref)))) {
xlb <- paste(xlabel(xvardef("iwres",object),object), " (Run ", object@Runno, ")",sep="")
ylb <- paste(xlabel(xvardef("iwres",object.ref),object.ref), " (Run ", object.ref@Runno, ")",sep="")
main <- paste(ylb, " vs ", xlb, sep="")
xplot4 <- xpose.plot.default(xvardef("iwres", object),
"IWRES.REF",
object,
xlb = xlb,
ylb = ylb,
main = NULL,
abline=c(0,1),
onlyfirst = onlyfirst,
inclZeroWRES = inclZeroWRES,
subset = subset,
...)
}
## create enpty list for plots
num.of.plots <- 4
plotList <- vector("list",num.of.plots)
plotList[[1]] <- xplot1
plotList[[2]] <- xplot2
plotList[[3]] <- xplot3
plotList[[4]] <- xplot4
default.plot.title <- "Basic model comparison plots"
plotTitle <- xpose.multiple.plot.title(object=object,
plot.text = default.plot.title,
subset=subset,
main=main,
...)
obj <- xpose.multiple.plot(plotList,plotTitle,...)
return(obj)
}
| /scratch/gouwar.j/cran-all/cranData/xpose4/R/basic.model.comp.R |
#' Function to create histograms of results from the \code{bootstrap} tool in
#' \href{https://uupharmacometrics.github.io/PsN/}{PsN}
#'
#' Reads results from the \code{bootstrap} tool in \href{https://uupharmacometrics.github.io/PsN/}{PsN}
#' and then creates histograms.
#'
#'
#' @param results.file The location of the results file from the
#' \code{bootstrap} tool in \href{https://uupharmacometrics.github.io/PsN/}{PsN}
#' @param incl.ids.file The location of the included ids file from the
#' \code{bootstrap} tool in \href{https://uupharmacometrics.github.io/PsN/}{PsN}
#' @param min.failed Should NONMEM runs that had failed minimization be
#' skipped? \code{TRUE} or \code{FALSE}
#' @param cov.failed Should NONMEM runs that had a failed covariance step be
#' skipped? \code{TRUE} or \code{FALSE}
#' @param cov.warnings Should NONMEM runs that had covariance step warnings be
#' skipped? \code{TRUE} or \code{FALSE}
#' @param boundary Should NONMEM runs that had boundary warnings be skipped?
#' \code{TRUE} or \code{FALSE}
#' @param showOriginal Should we show the value from the original NONMEM run in
#' the histograms? \code{TRUE} or \code{FALSE}
#' @param showMean Should we show the mean of the histogram data? \code{TRUE}
#' or \code{FALSE}
#' @param showMedian Should we show the median of the histogram data?
#' \code{TRUE} or \code{FALSE}
#' @param showPCTS Should we show the percentiles of the histogram data?
#' \code{TRUE} or \code{FALSE}
#' @param PCTS the percentiles to show. Can be a vector of any length. For
#' example, \code{c(0.05,0.2,0.5,0.7)}
#' @param excl.id Vector of id numbers to exclude.
#' @param layout Layout of plots. A vector of number of rows and columns in
#' each plot. \code{c(3,3)} for example.
#' @param sort.plots Should the plots be sorted based on type of parameter.
#' Sorting on parameters, standard errors, shrinkage and eigenvalues.
#' @param main The title of the plot.
#' @param \dots Additional arguments that can be passed to
#' \link{xpose.plot.histogram}, \link{xpose.panel.histogram},
#' \link[lattice]{histogram} and other \link[lattice]{lattice-package}
#' functions.
#' @return A lattice object
#' @author Andrew Hooker
#' @seealso \link{xpose.plot.histogram}, \link{xpose.panel.histogram},
#' \link[lattice]{histogram} and other \link[lattice]{lattice-package}
#' functions.
#' @references \href{https://uupharmacometrics.github.io/PsN/}{PsN}
#' @keywords methods
#' @examples
#'
#' \dontrun{
#' boot.hist(results.file="./boot1/raw_results_run1.csv",
#' incl.ids.file="./boot1/included_individuals1.csv")
#' }
#'
#' @export
#' @importFrom utils read.csv
#' @family PsN functions
boot.hist <-
function(results.file="raw_results_run1.csv",
incl.ids.file="included_individuals1.csv",
min.failed=FALSE, # do we want to omit minimization failed runs?
cov.failed=FALSE, # do we want to omit covariance failed runs?
cov.warnings=FALSE, # do we want to omit covariance failed runs?
boundary=FALSE, # do we want to omit boundary runs?
showOriginal=TRUE, # show line for original estimate
showMean=FALSE, # show line for mean
showMedian=FALSE, # show line for median
showPCTS=FALSE, # show line for confidence interval (percentile)
PCTS = c(0.025,0.975), # vector of percentiles to plot, can be any length
excl.id=c(), # exclude samples that have this individual
layout = NULL, # layout for plot, e.g. c(3,3)
sort.plots=TRUE,
main = "Default",
...)
{
## for testing
## results.file="./boot1/raw_results_run1.csv"
## incl.ids.file="./boot1/included_individuals1.csv"
## min.failed=FALSE # do we want to omit minimization failed runs?
## cov.failed=FALSE # do we want to omit covariance failed runs?
## cov.warnings=FALSE # do we want to omit covariance failed runs?
## boundary=FALSE # do we want to omit boundary runs?
## showoriginal=TRUE # show line for original estimate
## showmean=TRUE # show line for mean
## showmedian=FALSE # show line for median
## showPCTS=TRUE # show line for confidence interval (percentile)
## CI.limits = c(0.025, 0.975)
## showquart=FALSE # show line for quartiles
## excl.id=c() # exclude samples that have this individual
## layout=c(3,3)
## read files
bootstrap.data <- read.csv(results.file)
incl.ids <- read.csv(incl.ids.file, header=F)
## replace underscores
for (i in 1:length(names(bootstrap.data))) {
names(bootstrap.data)[i] <- gsub("_", ".", names(bootstrap.data)[i])
}
## find ofv column index
index <- 0
seen <- FALSE
for (i in names(bootstrap.data)) {
if (!seen) {
index <- index + 1
}
if (i == "ofv") {
seen <- TRUE
}
}
## get number of parameters
n <- length(colnames(bootstrap.data)) - index
nparams <- length(colnames(bootstrap.data))
## separate out original model fit
p1 <- subset(bootstrap.data, bootstrap.data$model != 0)
o1 <- subset(bootstrap.data, bootstrap.data$model == 0)
## get all names
all.index <- c(index:nparams)
all.names <- names(p1)[all.index]
## get ofv index and name
ofv.index <- grep("^ofv$",names(p1[index:nparams]))
ofv.names <- names(p1[index:nparams])[ofv.index]
##ofv.names
##ofv.index
## get SE indexexes and names
se.index <- grep("^se",names(p1[index:nparams]))
se.names <- names(p1[index:nparams])[se.index]
##se.names
##se.index
## get eigenvalue indexexes and names
ei.index <- grep("^EI",names(p1[index:nparams]))
ei.names <- names(p1[index:nparams])[ei.index]
##ei.index
##ei.names
## get shrinkage indexexes and names
sh.index <- grep("^shrinkage",names(p1[index:nparams]))
sh.names <- names(p1[index:nparams])[sh.index]
##sh.index
##sh.names
## get parameter names and index
par.names <- names(p1[index:nparams])[-c(ofv.index,sh.index,ei.index,se.index)]
par.index <- grep("*",names(p1[index:nparams]))[-c(ofv.index,sh.index,ei.index,se.index)]
##par.names
##par.index
incl.flag <- rep(0,length(rownames(p1)))
for( i in excl.id ) {
incl.flag <- incl.flag + rowSums( incl.ids == i )
}
p1 <- p1[(incl.flag==0),]
#names(p1)[2] <- "minimization.successful"
#names(p1)[3] <- "covariance.step.successful"
#names(p1)[4] <- "covariance.step.warnings"
#names(p1)[5] <- "estimate.near.boundary"
#cat(nrow(p1))
if (min.failed) {
p1 <- p1[p1$minimization.successful==1,]
}
if (cov.failed) {
p1 <- p1[p1$covariance.step.successful==1,]
}
if (cov.warnings) {
p1 <- p1[p1$covariance.step.warnings==0,]
}
if (boundary) {
p1 <- p1[p1$estimate.near.boundary==0,]
}
## check that classes are present
#createXposeClasses()
if (!isClass("xpose.data") || !isClass("xpose.prefs")) {
createXposeClasses()
}
## Create the object
xpobj <- new("xpose.data",
Runno="PsN Bootstrap",
Data = NULL)
## read local options
if (is.readable.file("xpose.ini")) {
xpobj <- xpose.read(xpobj, file="xpose.ini")
} else {
## read global options
rhome <- R.home()
xdefini <- paste(rhome, "\\library\\xpose4\\xpose.ini", sep="")
if (is.readable.file(xdefini)) {
xpobj <- xpose.read(xpobj, file=xdefini)
}else{
xdefini2 <- paste(rhome, "\\library\\xpose4\\xpose.ini", sep="")
if (is.readable.file(xdefini2)) {
xpobj <- xpose.read(xpobj, file=xdefini2)
}
}
}
p1$ID <-1
p1$WRES <- 1
Data(xpobj) <- p1
if(sort.plots){
plot1 <- xpose.plot.histogram(par.names,xpobj,
bins.per.panel.equal=FALSE,
layout=layout,
vdline=if(showOriginal){c(o1[all.index][par.index])} else {NULL},
showMean=showMean,
showMedian=showMedian,
showPCTS=showPCTS,
main=if(main=="Default"){"Parameters in Bootstrap"}else{main},
...)
plot2 <- NULL
plot4 <- NULL
plot5 <- NULL
if(!all(is.na(p1[se.names]))){
plot2 <- xpose.plot.histogram(se.names,xpobj,
bins.per.panel.equal=FALSE,
layout=layout,
vdline=if(showOriginal){c(o1[all.index][se.index])} else {NULL},
showMean=showMean,
showMedian=showMedian,
showPCTS=showPCTS,
main=if(main=="Default"){"Standard Errors of Parameters in Bootstrap"}else{main},
...)
}
plot3 <- xpose.plot.histogram(ofv.names,xpobj,
bins.per.panel.equal=FALSE,
layout=layout,
vdline=if(showOriginal){c(o1[all.index][ofv.index])} else {NULL},
showMean=showMean,
showMedian=showMedian,
showPCTS=showPCTS,
main=if(main=="Default"){"Objective Function in Bootstrap"}else{main},
...)
if(!all(is.na(p1[ei.names]))){
plot4 <- xpose.plot.histogram(ei.names,xpobj,
bins.per.panel.equal=FALSE,
layout=layout,
vdline=if(showOriginal){c(o1[all.index][ei.index])} else {NULL},
showMean=showMean,
showMedian=showMedian,
showPCTS=showPCTS,
main=if(main=="Default"){"Eigenvalues in Bootstrap"}else{main},
...)
}
if(!all(is.na(p1[sh.names]))){
plot5 <- xpose.plot.histogram(sh.names,xpobj,
bins.per.panel.equal=FALSE,
layout=layout,
vdline=if(showOriginal){c(o1[all.index][sh.index])} else {NULL},
showMean=showMean,
showMedian=showMedian,
showPCTS=showPCTS,
main=if(main=="Default"){"Shrinkage in Bootstrap"}else{main},
...)
}
return(list(plot1,plot2,plot3,plot4,plot5))
}
xpose.plot.histogram(all.names,xpobj,
bins.per.panel.equal=FALSE,
layout=layout,
vdline=if(showOriginal){c(o1[all.index])} else {NULL},
showMean=showMean,
showMedian=showMedian,
showPCTS=showPCTS,
main=if(main=="Default"){"Bootstrap Histogram"}else{main},
...)
#xpose.plot.histogram(all.names,xpobj,bins.per.panel.equal=FALSE,vdline=c(o1[all.index]))
## xpose.plot.histogram(names(p1)[index:nparams],xpobj,bins.per.panel.equal=FALSE,layout=layout)
## xpose.plot.histogram(names(p1)[index:nparams],xpobj,bins.per.panel.equal=FALSE,layout=c(4,5),showMean=T,showMedian=T,showPCTS=T)
## xpose.plot.histogram(names(p1)[index:nparams],xpobj,bins.per.panel.equal=FALSE,layout=c(4,5),vdline=c(o1[index:nparams]))
## xpose.plot.histogram(par.names,xpobj,bins.per.panel.equal=FALSE,vdline=c(o1[index:nparams][par.index]))
## xpose.plot.histogram(c("X1.BASELINE"),xpobj)
## xpose.plot.histogram(c("X1.BASELINE","X2.PLACEBO.MAX"),xpobj,bins.per.panel.equal=FALSE)
## plot.names <- names(p1)[index:nparams]
## xpose.plot.histogram(plot.names,xpobj,bins.per.panel.equal=FALSE,layout=c(3,3))
## xpose.plot.histogram(c("X1.BASELINE","ofv","X4.SLP","X2.PLACEBO.MAX","X3.PLACEBO.HL"),xpobj,bins.per.panel.equal=FALSE)
## xpose.plot.histogram(c("X1.BASELINE","ofv","X4.SLP","X3.PLACEBO.HL"),xpobj,bins.per.panel.equal=FALSE)
## xpose.plot.histogram(c("se1.BASELINE"),xpobj)
## xpose.plot.histogram(c("se1.BASELINE","X2.PLACEBO.MAX"),xpobj,bins.per.panel.equal=FALSE)
## xpose.plot.histogram(c("X1.BASELINE","X2.PLACEBO.MAX"),xpobj,bins.per.panel.equal=FALSE)
## xpose.plot.histogram(c("X1.BASELINE","X2.PLACEBO.MAX"),xpobj,bins.per.panel.equal=FALSE)
## xpose.plot.histogram(c("X1.BASELINE","X3.PLACEBO.HL"),xpobj,bins.per.panel.equal=FALSE)
## library(reshape2)
## #stack.params <- stack(ree.aod,select=c(thCl,thV,thMax,thE50,thHill))
## #stack.fix <- stack(ree.fix,select=c(thCl,thV,thMax,thE50,thHill))
## library(ggplot2)
## p <- ggplot(data=p1,aes(X1.BASELINE))
## p + geom_histogram()
## + geom_jitter(position=position_jitter(width=0.05)) + facet_grid(~type)
## ## stats and plots for each- single
## for (i in index:nparams) {
## if (mode(p1[[i]]) == "numeric" &&
## sum(p1[[i]],na.rm=T)) {
## sp <- summary(p1[[i]])
## # IQR <- diff(summary(p1[[i]])[c(5,2)])
## dp <- density(p1[[i]], na.rm=T)
## parmlabel <- names(p1)[i]
## #pdf(file=paste("bootstrap.", parmlabel, ".pdf", sep=""), paper="special",
## # title=paste("Bootstrap results - ", parmlabel, sep=""),width=10,height=7 )
## qu <- quantile(p1[[i]], CI.limits, na.rm=T)
## legend=paste("n = ", nrow(p1), sep="")
## if (showmean) {
## legend=paste(legend, "; Mean = ", sp[4], sep="")
## }
## if (showmedian) {
## legend=paste(legend, "; Median = ", sp[3], sep="")
## }
## if (showoriginal) {
## legend=paste(legend, "; Orig = ", o1[[i]], sep="")
## }
## hist(p1[[i]],
## main = paste("Bootstrap results - ", parmlabel, sep=""),
## xlab = parmlabel,
## # ylim = c(0, max(dp$y)),
## # ylim = c(0, 1),
## xlim = c(min(dp$x), max(dp$x)),
## breaks = 20,
## # xlim = c(min(p1[[i]]) - min(p1[[i]])*0.15,max(p1[[i]]) + max(p1[[i]])*0.15),
## probability = T,
## sub=legend )
## # sub=paste(paste(paste("n = ", nrow(p1), sep=""), "; Median = ", sp[4], sep=""), "; Orig = ", o1[[i]], sep="") )
## #h <- hist(p1[[i]], prob=T, plot=F)
## lines(dp, lwd=2, lty=3, col="red")
## if (showquart) {
## abline(v=sp[2], lwd= 1, lty=3, col="red") ## 1st quartile
## abline(v=sp[5], lwd= 1, lty=3, col="red") ## 3rd quartile
## }
## if (showmean) {
## abline(v=sp[4], lty=2, lwd=1, col="red") ## mean
## }
## if (showmedian) {
## abline(v=sp[3], lty=1, lwd=2, col="red") ## median
## }
## if (showoriginal) {
## abline(v=o1[[i]], lty=2, lwd=1, col="red") ## original
## }
## if (show95CI) {
## abline(v=qu[1], lty=4, lwd=1, col="red") ## 2.5% CL
## abline(v=qu[2], lty=4, lwd=1, col="red") ## 97.5% CL
## text(qu[1], max(dp$y), labels=signif(qu[1], digits = 3), cex = .8, adj = c(0,0), pos='2')
## text(qu[2], max(dp$y), labels=signif(qu[2], digits = 3), cex = .8, adj = c(0,0), pos='4')
## }
## # abline(v=sp[4], lty=1, lwd=2, col="red") ## median
## # abline(v=o1[[i]], lty=2, lwd=1, col="red") ## original
## # abline(v=qu[1], lty=4, lwd=1, col="red") ## 2.5% CL
## # abline(v=qu[2], lty=4, lwd=1, col="red") ## 97.5% CL
## # text(qu[1], max(dp$y), labels=signif(qu[1], digits = 3), cex = .8, adj = c(0,0), pos='2')
## # text(qu[2], max(dp$y), labels=signif(qu[2], digits = 3), cex = .8, adj = c(0,0), pos='4')
## #text(sp[4], max(h$density), labels=paste("Med: ", signif(sp[4], digits = 3), sep=""), adj = c(-1,0), cex = .8, pos='2')
## }
## }
## stats and plots for each - 6 per sheet
## total <- 0
## bspage <- 0
## for (i in index:nparams) {
## if (mode(p1[[i]]) == "numeric" &&
## sum(p1[[i]],na.rm=T)) {
## sp <- summary(p1[[i]])
## # IQR <- diff(summary(p1[[i]])[c(5,2)])
## dp <- density(p1[[i]], na.rm=T)
## parmlabel <- names(p1)[i]
## if (total == 0) {
## bspage <- bspage + 1
## pdf(file=paste("bootstrap.page", bspage, ".pdf", sep=""), paper="special",
## title="Bootstrap results",width=10,height=7)
## par(mfrow = c(3,3))
## }
## total <- total + 1
## qu <- quantile(p1[[i]], c(0.025, 0.975), na.rm=T)
## legend=paste("n = ", nrow(p1), sep="")
## if (showmean) {
## legend=paste(legend, "; Mean = ", sp[3], sep="")
## }
## if (showmedian) {
## legend=paste(legend, "; Median = ", sp[4], sep="")
## }
## if (showoriginal) {
## legend=paste(legend, "; Orig = ", o1[[i]], sep="")
## }
## hist(p1[[i]],
## main = paste("Bootstrap results - ", parmlabel, sep=""),
## xlab = parmlabel,
## # ylim = c(0, max(dp$y)),
## # ylim = c(0, 1),
## xlim = c(min(dp$x), max(dp$x)),
## breaks = 20,
## # xlim = c(min(p1[[i]]) - min(p1[[i]])*0.15,max(p1[[i]]) + max(p1[[i]])*0.15),
## probability = T,
## sub=legend )
## #=paste(paste(paste("n = ", nrow(p1), sep=""), "; Median = ", sp[4], sep=""), "; Orig = ", o1[[i]], sep="") )
## #h <- hist(p1[[i]], prob=T, plot=F)
## lines(dp, lwd=2, lty=3, col="red")
## if (showquart) {
## abline(v=sp[2], lwd= 1, lty=3, col="red") ## 1st quartile
## abline(v=sp[5], lwd= 1, lty=3, col="red") ## 3rd quartile
## }
## if (showmean) {
## abline(v=sp[3], lty=2, lwd=1, col="red") ## mean
## }
## if (showmedian) {
## abline(v=sp[4], lty=1, lwd=2, col="red") ## median
## }
## if (showoriginal) {
## abline(v=o1[[i]], lty=2, lwd=1, col="red") ## original
## }
## if (show95CI) {
## abline(v=qu[1], lty=4, lwd=1, col="red") ## 2.5% CL
## abline(v=qu[2], lty=4, lwd=1, col="red") ## 97.5% CL
## text(qu[1], max(dp$y), labels=signif(qu[1], digits = 3), cex = .8, adj = c(0,0), pos='2')
## text(qu[2], max(dp$y), labels=signif(qu[2], digits = 3), cex = .8, adj = c(0,0), pos='4')
## }
## # abline(v=sp[4], lty=1, lwd=2, col="red") ## median
## # abline(v=o1[[i]], lty=2, lwd=1, col="red") ## original
## # abline(v=qu[1], lty=4, lwd=1, col="red") ## 2.5% CL
## # abline(v=qu[2], lty=4, lwd=1, col="red") ## 97.5% CL
## # text(qu[1], max(dp$y), labels=signif(qu[1], digits = 3), cex = .8, adj = c(0,0), pos='2')
## # text(qu[2], max(dp$y), labels=signif(qu[2], digits = 3), cex = .8, adj = c(0,0), pos='4')
## #text(sp[4], max(h$density), labels=paste("Med: ", signif(sp[4], digits = 3), sep=""), adj = c(-1,0), cex = .8, pos='2')
## if (total == 9) {
## total <- 0
## dev.off()
## }
## }
## }
## while(names(dev.cur())=="pdf"){dev.off()}
## #for(i in 1:17){
## # dev.off()
## #}
}
| /scratch/gouwar.j/cran-all/cranData/xpose4/R/boot.hist.R |
xp.bootgam <- function (object,
n = NULL, # number of bootstrap iterations
id = "ID", # column name of id
oid = "OID", # create a new column with the original ID data
seed = NULL, # random seed
parnam = xvardef("parms", object),
covnams = xvardef("covariates", object),
wts.col = NULL,
ask.for.input = TRUE,
overwrite = TRUE,
...) {
ask.for.n <- function(...) {
cat("\nEnter maximum number of bootstrap replicates to perform in bootGAM (0 to exit): ")
ans <- as.numeric(readline())
if ((!is.numeric(ans)) || (is.na(ans))) {
cat("\nPlease specify a number.\n")
ans <- Recall(...)
}
return(as.numeric(ans))
}
ask.for.seed <- function(...) {
cat("\nSpecify a seed number for the bootstrap (0 to exit): ")
ans <- as.numeric(readline())
if ((!is.numeric(ans)) || (is.na(ans))) {
cat("\nPlease specify a number.\n")
ans <- Recall(...)
}
if (ans == 0) {
return(NULL)
}
return(as.numeric(ans))
}
ask.for.par <- function(...) {
cat("\nEnter name of parameter to use for this bootGAM (0 to exit): ")
ans <- readline()
if (ans == 0) {
return(NULL)
}
if (length(ans) > 1) {
cat("\nYou have specified more than one parameter.\n")
cat("The bootGAM can be run on only one parameter at a time.\n")
ans <- Recall(...)
}
else {
ans.exists <- check.vars(ans, object)
if (is.null(ans.exists)) {
ans <- Recall(...)
}
}
return(ans)
}
get.par <- function(nams, get.input = FALSE, ...) {
ans <- NULL
if (length(nams) == 0) {
cat("\nNo parameter is defined for this bootGAM\n")
if (get.input) {
ans <- ask.for.par()
}
else {
cat("\nType '?xp.bootgam' for more information.\n")
}
}
if (length(nams) > 1) {
cat("\nThere is more than one parameter defined\n")
cat("for this bootGAM. The parameters defined are:\n\n")
cat(nams, fill = 60)
cat("\nThe bootGAM can be run on only one parameter at a time.\n")
if (get.input) {
ans <- ask.for.par()
}
else {
cat("\nType '?xp.bootgam' for more information.\n")
}
}
if (length(nams) == 1) {
ans <- nams
}
return(ans)
}
ask.for.wts <- function(...) {
cat("\nWeight column to use (0 to exit, NULL for no weight):")
ans <- readline()
if (ans == "NULL")
return("NULL")
if (ans == 0)
return(NULL)
if (length(ans) > 1) {
cat("\nYou have specified more than one weight.\n")
cat("Only one weight is allowed.\n")
ans <- Recall(...)
}
else {
if (is.na(pmatch(ans, names([email protected])))) {
cat(paste("\n", "-----------Variable(s) not defined!-------------\n",
ans, "is not defined in the current database\n",
"and must be defined for this command to work!\n",
"------------------------------------------------\n"))
ans <- Recall(...)
}
return(ans)
}
}
get.wts <- function(nams, get.input = FALSE, ...) {
ans <- NULL
if (length(nams) == 0) {
cat("\nNo weights are defined for this bootGAM\n")
if (get.input) {
ans <- ask.for.wts()
}
else {
cat("\nType '?xp.bootgam' and '?xpose.bootgam' for more information.\n")
}
}
if (length(nams) > 1) {
cat("\nPlease specify a the weights for the parameter.\n")
cat("The weights come from columns in the data contained\n")
cat("in the Data.firstonly section of the xpose data object.\n")
cat("These values usualy come from the .phi file of a NONMEM run.\n")
cat("Possible weight values (column names) are:\n\n")
cat(nams, fill = 60)
cat("\nOnly one weight can be specified.\n")
if (get.input) {
ans <- ask.for.wts()
}
else {
cat("\nType '?xp.bootgam' and '?xpose.bootgam' for more information.\n")
}
}
if (length(nams) == 1) {
ans <- nams
}
return(ans)
}
pars <- get.par(parnam, get.input = ask.for.input, ...)
if (is.null(pars)) {
return(invisible())
}
if (object@[email protected]$n) {
n <- object@[email protected]$n
} else {
if (ask.for.input) {
n <- ask.for.n()
if (is.null(n)) {
return(invisible())
}
}
}
if (object@[email protected]$wts & ask.for.input) {
wts <- get.wts(names([email protected]), get.input = ask.for.input,
...)
if (is.null(wts)) {
return(invisible())
}
if (wts == "NULL") {
wts <- NULL
}
wts.col <- wts
}
if (exists(paste("bootgam.xpose.", pars, ".", object@Runno, sep = ""),
where = 1) & !overwrite) {
if (ask.for.input) {
cat("\nThere is already a bootgam object associated with the current\n")
cat("run number and parameter. It will be overwritten if you proceed.\n")
cat("Proceed? n(y): ")
ans <- readline()
if (ans != "y") {
return()
}
}
else {
cat("\nThere is already a bootgam object associated with the current\n")
cat("run number and parameter. It will NOT be overwritten.\n")
return()
}
}
# Invoke actual bootGAM
if (is.null(seed)) {
seed <- ask.for.seed()
if (is.null(seed)) {
return(invisible)
}
}
bootgam.obj <- xpose.bootgam (object, # Xpose database
n = n, # number of replicates
id = object@Prefs@Xvardef$id, # column label of id
oid = "OID", # create a new column with the original ID data
seed = seed, # random seed
parnam = pars,
covnams = covnams,
wts.col = wts.col,
...)
cat ("\nBootstrap completed\n")
if (bootgam.obj$algo == "fluct.ratio") {
cat (paste("Fluctuation ratio: ", bootgam.obj$fluct.ratio.last, "\n\n", sep = ""))
} else {
cat (paste("Lowest absolute joint inclusion frequency: ", bootgam.obj$ljif.last, "\n\n", sep = ""))
}
if (length(bootgam.obj$failed[bootgam.obj$failed == 1]) > 0) {
cat ("Note: the gam failed for the following bootstrap replicate(s), since not all\ncovariates had enough levels (>1) in the dataset: \n")
cat (paste ( seq(1:n)[bootgam.obj$failed == 1] ) )
cat ("\nThese bootstrap replicates will not be used in summaries or diagnostic plots.\n")
cat ("\n\n")
}
c1 <- call("assign",pos = 1, paste("bootgam.xpose.", pars, ".", object@Runno,
sep = ""), bootgam.obj, immediate = T)
eval(c1)
if (exists("current.bootgam", where = 1)) {
remove(pos = 1, "current.bootgam")
}
c2 <- call("assign",pos = 1, "current.bootgam", bootgam.obj, immediate = T)
eval(c2)
return(invisible(bootgam.obj))
}
data.long <- function (data) { # same as melt() in reshape: create a dataframe in the long format based on a matrix/data.frame (for xyplot)
all <- c()
for (i in seq(along=colnames(data))) {
all <- data.frame (rbind (all, cbind(var = colnames(data)[i], row = 1:length(data[,1]), value = data[[colnames(data)[i]]] )))
}
all[,2] <- as.numeric(as.character(all[,2]))
all[,3] <- as.numeric(as.character(all[,3]))
return (all)
}
#' Title
#'
#' @inheritParams xpose.gam
#' @param n number of bootstrap iterations
#' @param id column name of id
#' @param oid create a new column with the original ID data
#' @param seed random seed
#' @param conv.value Convergence value
#' @param check.interval How often to check the convergence
#' @param start.check When to start checking
#' @param algo Which algorithm to use
#' @param start.mod which start model
#' @param liif The liif value
#' @param ljif.conv The convergence value for the liif
#' @param excluded.ids ID values to exclude.
#'
#' @return a list of results from the bootstrap of the GAM.
#' @export
#' @family GAM functions
#'
#' @examples
#'
#' \dontrun{
#' ## filter out occasion as a covariate as only one value
#' all_covs <- xvardef("covariates",simpraz.xpdb)
#' some_covs <- all_covs[!(all_covs %in% "OCC") ]
#'
#' ## here only running n=5 replicates to see that things work
#' ## use something like n=100 for resonable results
#' boot_gam_obj <- xpose.bootgam(simpraz.xpdb,5,parnam="KA",covnams=some_covs,seed=1234)
#' }
#'
xpose.bootgam <- function (object,
n = n, # number of bootstrap iterations
id = object@Prefs@Xvardef$id, # column name of id
oid = "OID", # create a new column with the original ID data
seed = NULL, # random seed
parnam = xvardef("parms", object)[1],
covnams = xvardef("covariates", object),
conv.value = object@[email protected]$conv.value,
check.interval = as.numeric(object@[email protected]$check.interval),
start.check = as.numeric(object@[email protected]$start.check),
algo = object@[email protected]$algo,
start.mod = object@[email protected]$start.mod,
liif = as.numeric(object@[email protected]$liif),
ljif.conv = as.numeric(object@[email protected]$ljif.conv),
excluded.ids = as.numeric(object@[email protected]$excluded.ids),
...) {
ids <- unique (object@Data[[id]])
if (!is.null(seed)) {
set.seed (seed)
}
## create template object
bootgam.obj <- list("results.raw" = list(),
"results.tab" = data.frame (matrix(0, nrow = n, ncol=length(covnams),
dimnames = list(NULL, covnams))),
"incl.freq" = data.frame (matrix(0, nrow = n, ncol=length(covnams),
dimnames = list(NULL, covnams))),
"oid" = data.frame (matrix(0, nrow = n, ncol=length(ids))),
"seed" = seed,
"runno" = object@Runno,
"failed" = rep(0, n),
"parnam" = parnam,
"covnams" = covnams,
"n" = n,
"conv.value" = conv.value,
"check.interval" = check.interval,
"start.check"= start.check,
"algo" = algo,
"start.mod" = start.mod,
"liif" = liif,
"ljif.conv" = ljif.conv,
"excluded.ids" = excluded.ids,
"fluct.ratio.last" = NULL,
"ljif.last" = NULL
)
## Define convergence criteria
get.crit1 <- function(cov.table, check.interval, i, conv) {
#cov.table <- current.bootgam$incl.freq
n.del <- sum(apply (cov.table[1:i,], 1, sum) == 0)
i <- i - n.del
cov.table <- cov.table[apply (cov.table, 1, sum) > 0,] # unselect failed gams
i.start <- i - check.interval
if (i.start < 1) {i.start <- 1}
min.int <- apply (cov.table[i.start:i,], 2, min)
max.int <- apply (cov.table[i.start:i,], 2, max)
prob <- apply(cov.table[i.start:i, ], 2, mean)
del <- min.int != 0 # if min.int is 0, then division by zero! remove those
min.int <- min.int[del]
max.int <- max.int[del]
prob <- prob[del]
crit <- sum((max.int/min.int) * prob)/sum(prob)
cnv <- 0
if(!is.na(crit)) {
if(is.numeric(crit) && (crit < conv)) {
cnv <- 1
}
}
retrn <- c(crit, cnv)
return(retrn)
}
get.crit2 <- function(ind.mat, i, liif = 0.2, ljif.conv = 25, failed) {
ind.mat <- ind.mat[failed == 0,]
n.del <- sum(failed[1:i])
i <- i - n.del
min.inc <- min(apply(ind.mat[1:i,], 2, mean))
f.low <- i * min.inc * liif
cnv <- 0
if(f.low >= ljif.conv) {
cnv <- 1
}
retrn <- c (f.low,cnv)
return(retrn)
}
## Initialize bootstrap
cat (paste("\nStarting bootstrap (max ", n, " replicates, seed = ", seed,").\n", sep=""))
cat ("Bootgam progress:\n")
pb <- txtProgressBar(min=0, max=n, initial=1, style=3)
next.check <- as.numeric(start.check)
i <- 1
## filter out excluded individuals (if exist in dataset)
for (i in seq(along=excluded.ids)) {
if (excluded.ids[i] %in% object@Data[[id]]) {
object@Data <- object@Data[object@Data[[id]]!=excluded.ids[i],]
}
}
## The actual bootstrap loop
i <- 1
while (i <= n) {
setTxtProgressBar(pb, i)
bs.object <- object
bs.sample <- xpose.bootgam.drawsample (object@Data)
if (test.covariate.levels (bs.sample$Data, covnams) == 0) { # test number of levels
bs.object@Data <- bs.sample$Data # Bootstrapped dataset
for (k in seq(along = bs.sample$id)) {
bootgam.obj$oid[i,bs.sample$id[k]] <- bootgam.obj$oid[i,bs.sample$id[k]] + 1 # save original ID numbers selected in the bootstrap
}
capture.output ( # don't show all print output from the gam
gam.results <- xpose.gam (bs.object,
start.mod = start.mod,
parnam = bootgam.obj$parnam)
)
bootgam.obj$results.raw[[i]] <- gam.results
covs <- xpose.bootgam.extract.covnames(gam.results)
bootgam.obj$results.tab[i, match (covs, covnams)] <- 1
tmp <- bootgam.obj$results.tab[bootgam.obj$failed==0,]
bootgam.obj$incl.freq[i,] <- apply (tmp[1:(i-sum(bootgam.obj$failed)),], 2, mean)
} else {
bootgam.obj$results.tab[i, ] <- -99
bootgam.obj$failed[i] <- 1
}
## Convergence criteria
if(i == next.check) { # If it is time to check the convergence
next.check <- as.numeric(next.check) + as.numeric(check.interval)
## The criteria depends on the algo
if(algo == "fluct.ratio") {
crit.vec <- get.crit1(bootgam.obj$incl.freq, check.interval, i, conv.value)
bootgam.obj$fluct.ratio.last <- crit.vec[1]
} else {
crit.vec <- get.crit2(bootgam.obj$oid, i, liif, ljif.conv, bootgam.obj$failed)
bootgam.obj$ljif.last <- crit.vec[1]
}
cat (paste(" Conv. crit :", round(crit.vec[1],3), "\n"))
## Convergence!!
if(crit.vec[2] == 1) {
bootgam.obj$results.tab <- bootgam.obj$results.tab[1:i, ]
bootgam.obj$incl.freq <- bootgam.obj$incl.freq[1:i, ]
bootgam.obj$failed <- bootgam.obj$failed[1:i]
n <- 0 # stop the bootstrap
}
}
i <- i+1
}
close(pb)
return (bootgam.obj)
}
test.covariate.levels <- function (data, covariates) {
# all covariates must at least have more than 1 level to be able to run a gam, otherwise it will crash
flag <- 0
for (i in 1:length(covariates)) {
if (length(unique(data[[covariates[i]]])) < 2) {
flag <- 1
}
}
return (flag)
}
xpose.bootgam.extract.covnames <- function (gam.object) {
covs <- names(gam.object[1]$coefficients)[-1] # first element is intercept
covs <- gsub ("ns\\(", "", covs)
covs <- gsub ("\\,.*", "", covs)
covs <- gsub ("[0-9]*", "", covs)
return (unique (covs))
}
xpose.bootgam.drawsample <- function (data, # data.frame()
id = "ID", # column name of id
oid = "OID" # create a new column with the original ID data
) {
errors_encountered <- c()
## get vector with individuals in dataset
ids <- unique (data[[id]])
n_ids <- length(ids)
if (n_ids <= 1) {
errors_encountered <- c("Please check arguments supplied to bootstrap function.")
}
if (is.null(errors_encountered)) {# only draw bootstrap sample when dataset seems valid
## initialize bootstrap step
id_draw <- sample (n_ids, n_ids, replace = T)
bs_draw <- ids[id_draw]
if (length(oid) > 0) { # store original id number as new column
data[[oid]] <- data[[id]]
}
bs_data <- c()
## Loop over the ids that were drawn and give a new number
for (i in 1:n_ids) {
tmp_data <- data[data[[id]] == bs_draw[i],]
tmp_data[[id]] <- i # give a new id number
bs_data <- rbind (bs_data, tmp_data)
}
bs.sample <- list ("Data" = bs_data, "oid" = bs_draw, "id" = id_draw)
return (bs.sample)
}
}
| /scratch/gouwar.j/cran-all/cranData/xpose4/R/bootgam.R |
# Xpose 4
# An R-based population pharmacokinetic/
# pharmacodynamic model building aid for NONMEM.
# Copyright (C) 1998-2004 E. Niclas Jonsson and Mats Karlsson.
# Copyright (C) 2005-2008 Andrew C. Hooker, Justin J. Wilkins,
# Mats O. Karlsson and E. Niclas Jonsson.
# Copyright (C) 2009-2010 Andrew C. Hooker, Mats O. Karlsson and
# E. Niclas Jonsson.
# This file is a part of Xpose 4.
# Xpose 4 is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public License
# as published by the Free Software Foundation, either version 3
# of the License, or (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
# You should have received a copy of the GNU Lesser General Public License
# along with this program. A copy can be cound in the R installation
# directory under \share\licenses. If not, see http://www.gnu.org/licenses/.
set.max.replicates <- function (first = TRUE) {
value <- .cur.db@[email protected]$n
if (first == TRUE) {
cat("Number of (maximum) bootstrap replicates to perform \n")
if (is.null(value)) {
cat("The current value is NULL...\n")
}
else {
cat("The current number is", value, "...\n")
}
cat("\nPlease type the new number: ")
}
ans <- as.numeric(readline())
if (ans == "NULL" || ans == "null") {
Recall(first = FALSE)
} else {
if (ans > 0) {
.cur.db@[email protected]$n <- ans
c1 <- call("assign",pos = 1, ".cur.db", .cur.db)
eval(c1)
invisible()
return()
} else {
cat("Please enter a numeric value larger than 0 ")
Recall(first = FALSE)
}
}
}
bootgam.conv.crit1 <- function() {
cat("\nType the critical value of the fluctuation ratio\n")
cat("you want to use (0 to exit)\n")
ans <- readline()
if (ans == 0) {
return()
}
if (ans < 1) {
cat("The number must be greater than 1\n")
Recall()
}
.cur.db@[email protected]$crit1.conv <- ans
c2 <- call("assign",pos = 1, ".cur.db", .cur.db)
eval(c2)
invisible()
return()
}
bootgam.conv.crit2 <- function(skip=F) {
if(!skip) {
cat("\nType the lowest important relative inclusion frequency\n")
cat("or return for the default (0.2):")
ans <- readline()
if(ans == "") {
.cur.db@[email protected]$crit2.liif <- 0.2
} else if(ans < 0 || ans > 1) {
cat("The number must be greater than 0 and lower than 1\n")
Recall()
} else {
.cur.db@[email protected]$crit2.liif <- ans
}
}
cat("\nType the lowest absulute joint inclusion frequency\n")
cat("or return for the default (25):")
ans2 <- readline()
if(ans2 == "") {
.cur.db@[email protected]$crit2.ljif.conv <- 25
} else if(ans2 < 1) {
cat("The number must be greater than 1\n")
Recall(skip=T)
} else {
.cur.db@[email protected]$crit2.ljif.conv <- ans2
}
c3 <- call("assign",pos = 1, ".cur.db", .cur.db)
eval(c3)
invisible()
return()
}
specify.start.model <- function () {
if (any(is.null(covs <- xvardef("covariates", .cur.db)))) {
cat("\nThe current data base has no covariates defined\n")
invisible()
return()
}
cat("\nThe following covariates are defined in the current data base:\n")
cat(covs, fill = 60)
cat("\nType the names of the covariates that should be included in the\n")
cat("\nmodel and end with a blank line:\n")
st.covs <- scan(what = character())
if(length(st.covs) == 0) {
st.covs <- NULL
}
.cur.db@[email protected]$start.mod <- st.covs
c4 <- call("assign",pos = 1, ".cur.db", .cur.db)
eval(c4)
invisible()
return()
}
normalize.median <- function () {
if (.cur.db@[email protected]$median.norm == FALSE) {
.cur.db@[email protected]$median.norm <- TRUE
cat ("\nNormalize to median is now set to ON\n")
} else {
.cur.db@[email protected]$median.norm <- FALSE
cat ("\nNormalize to median is now set to OFF\n")
}
c5 <- call("assign",pos = 1, ".cur.db", .cur.db)
eval(c5)
invisible()
return()
}
bg.conv.crit2 <- function(skip = FALSE) {
if(!skip) {
cat("\nType the lowest important relative inclusion frequency\n")
cat("or return for the default (0.2):")
ans <- readline()
if(ans == "") {
.cur.db@[email protected]$liif <- 0.2
} else if(ans < 0 || ans > 1) {
cat("The number must be greater than 0 and lower than 1\n")
Recall()
} else {
.cur.db@[email protected]$liif <- ans
}
}
cat("\nType the lowest absulute joint inclusion frequency\n")
cat("or return for the default (25):")
ans2 <- readline()
if(ans2 == "") {
.cur.db@[email protected]$ljif.conv <- 25
} else if(ans2 < 1) {
cat("The number must be greater than 1\n")
Recall(skip=T)
} else {
.cur.db@[email protected]$ljif.conv <- ans2
}
c6 <- call("assign",pos = 1, ".cur.db", .cur.db)
eval(c6)
invisible()
return()
}
bg.conv.crit1 <- function() {
cat("\nType the critical value of the fluctuation ratio\n")
cat("you want to use (0 to exit)\n")
ans <- readline()
if(ans == 0) {
return()
}
if(ans < 1) {
cat("The number must be greater than 1\n")
Recall()
}
.cur.db@[email protected]$conv.value <- ans
c7 <- call("assign",pos = 1, ".cur.db", .cur.db)
eval(c7)
invisible()
return()
}
change.conv.alg <- function () {
cat("\nSpecify the algorithm for convergence calculations\n")
choices <- c("Return to previous menu",
"Fluctuation ratio",
"Lowest absolute joint inclusion frequency"
)
pick <- menu(choices)
switch(pick,
return(),
{ .cur.db@[email protected]$algo <- "fluct.ratio"
c8 <- call("assign",pos = 1, ".cur.db", .cur.db)
eval(c8)
bg.conv.crit1()
},
{ .cur.db@[email protected]$algo <- "liif"
c9 <- call("assign",pos = 1, ".cur.db", .cur.db)
eval(c9)
bg.conv.crit2()
})
Recall()
return()
}
specify.start.check <- function () {
cat("\nType the iteration number at which you want to start checking\n")
cat("convergence (0 to exit):")
ans <- readline()
if(ans == 0) {
return()
}
if(ans < 0) {
cat("The number must be positive.\n")
Recall()
}
.cur.db@[email protected]$start.check <- ans
c10 <- call("assign",pos = 1, ".cur.db", .cur.db)
eval(c10)
invisible()
return()
}
specify.interval <- function () {
cat("\nType the interval at which the convergence should be \n")
cat("checked (0 to exit):")
ans <- readline()
if (ans == 0) {
return()
}
if (ans < 0) {
cat ("The number must be positive.\n")
Recall()
}
.cur.db@[email protected]$check.interval <- ans
c11 <- call("assign",pos = 1, ".cur.db", .cur.db)
eval(c11)
invisible()
return()
}
exclude.individuals <- function () {
cat("Please type the ID number of the individuals you want to exclude\n")
cat("from the bootgam analysis and finish with a blank line:\n")
inds <- scan(what = character())
if(length(inds) == 0) {
inds <- NULL
}
.cur.db@[email protected]$excluded.ids <- inds
c12 <- call("assign",pos = 1, ".cur.db", .cur.db)
eval(c12)
invisible()
return()
}
set.seed.number <- function () {
cat ("Type a seed number between 1 and 1000 (return to exit):")
ans <- readline()
if (ans == "") {
return()
}
if (as.numeric(ans) >= 1 && as.numeric(ans) <= 1000) {
.cur.db@[email protected]$seed <- ans
} else {
cat("The number must be between 1 and 1000\n")
Recall()
}
c13 <- call("assign",pos = 1, ".cur.db", .cur.db)
eval(c13)
}
bootgam.settings.menu <- function () {
choices <- c("Return to the previous menu ->",
"List current bootGAM settings",
"Set maximum number of bootstrap replicates",
"Change convergence algorithm",
"Specify iteration to start check convergence at",
"Specify at what interval to check the convergence",
"Set seed number",
"Exclude individuals",
"Specify starting model"
)
title = "\nBootGAM SETTINGS MENU\n \\main\\covariate model\\BootGAM\\settings for the BootGAM"
pick <- menu(choices, title = title)
qx <- 0
switch(pick + 1, qx <- 2, qx <- 1,
list.bootgam.settings(eval(as.name(".cur.db"))),
set.max.replicates(),
change.conv.alg(),
specify.start.check(),
specify.interval(),
set.seed.number(),
exclude.individuals(),
specify.start.model()
)
if (qx == 2) {
return(invisible(2))
}
else {
if (qx == 1) {
return(invisible(0))
}
else {
Recall()
}
}
}
list.bootgam.settings <- function (object) {
if (exists("object")) {
cat(paste("\nThe current run number is ", object@Runno, ".\n\n", sep = ""))
if (!any(is.null(object@Prefs@Xvardef$parms))) {
cat("\nMaximum number of bootstrap replicates: ", object@[email protected]$n)
cat(":", object@[email protected]$n)
cat("\nConvergence algorithm to use: ", object@[email protected]$algo)
if (object@[email protected]$algo == "fluct.ratio") {
cat("\nConvergence criterion: ", object@[email protected]$conv.value)
} else {
cat("\nLowest importan relative inclusion freq: ", object@[email protected]$liif)
cat("\nCritical value (ljif): ", object@[email protected]$ljif.conv)
}
cat("\nStarting model: ", object@[email protected]$n)
}
} else {
cat("The current run number is", object@Runno, "but no matching database was found.\n")
}
}
bootgam.menu <- function () {
choices <- c("Return to previous menu ->",
"Run a bootGAM",
"Summarize bootGAM",
"Plot bootGAM results ->",
"Settings for the BootGAM ->",
"Settings for the GAM ->")
title = "\nBootGAM MENU\n \\main\\covariate model\\BootGAM\n\n*** Note that the bootGAM also uses the settings from the GAM!\n Please go the GAM settings menu to alter these.\n"
pick <- menu(choices, title = title)
qx <- 0
switch(pick + 1, qx <- 2, qx <- 1,
xp.bootgam (eval(as.name(".cur.db")), overwrite = FALSE),
bootgam.print(),
qx <- bootgam.plot.menu(),
qx <- bootgam.settings.menu(),
qx <- gam.settings.menu())
if (qx == 2) {
return(invisible(2))
}
else {
if (qx == 1) {
return(invisible(0))
}
else {
Recall()
}
}
}
bootgam.plot.menu <- function () {
choices <- c("Return to previous menu",
"Inclusion frequencies",
"Most common 2-covariate combinations",
"Distribution of model size",
"Inclusion stability - covariates",
"Inclusion index of covariates",
"Inclusion index of covariates/individuals",
"Compare index of covariates/individuals"
)
title = "\nBootGAM plot MENU\n \\main\\covariate model\\BootGAM\\Plot"
pick <- menu(choices, title = title)
qx <- 0
switch(pick + 1, qx <- 2, qx <- 1,
print(xp.inc.prob()),
print(xp.inc.prob.comb.2()),
print(xp.distr.mod.size()),
print(xp.inc.stab.cov()),
print(xp.incl.index.cov()),
print(xp.incl.index.cov.ind()),
print(xp.incl.index.cov.comp())
)
if (qx == 2) {
return(invisible(2))
}
else {
if (qx == 1) {
return(invisible(0))
}
else {
Recall()
}
}
}
bootscm.plot.menu <- function ()
{
choices <- c("Return to previous menu ->",
"Inclusion frequencies",
"Most common 2-covariate combinations",
"Distribution of model size",
"Conditional inclusion index",
"Individual inclusion index",
"Compare index of covariates/individuals",
"Bias parameter estimates (hurricane plot)",
"Correlation in parameters covariate effects",
"Distribution of dOFV final models",
"dOFV versus model size final models",
"dAIC versus model size final models",
"Trace plots - parameter-covariates",
"Trace plots - conditional indices",
"Trace plots - indiv. conditional indices")
title = "\nBOOTSCM PLOT MENU\n \\main\\covariate model\\BootSCM\\Plot menu\n\n"
pick <- menu(choices, title = title)
qx <- 0
switch(pick + 1, qx <- 2, qx <- 1,
print(xp.inc.prob()),
print(xp.inc.prob.comb.2()),
print(xp.distr.mod.size()),
print(xp.incl.index.cov()),
print(xp.incl.index.cov.ind()),
print(xp.incl.index.cov.comp()),
print(xp.boot.par.est()),
print(xp.boot.par.est.corr(ask.covs = TRUE)),
print(xp.dofv.plot()),
print(xp.dofv.npar.plot()),
print(xp.daic.npar.plot()),
print(xp.inc.stab.cov()),
print(xp.inc.cond.stab.cov()),
print(xp.inc.ind.cond.stab.cov()))
if (qx == 2) {
return(invisible(2))
}
else {
if (qx == 1) {
return(invisible(0))
}
else {
Recall()
}
}
}
bootscm.menu <- function () {
choices <- c("Return to previous menu ->",
"Import bootSCM data (from PsN folder)",
"Summarize bootSCM",
"Plot menu"
)
title = "\nBOOTSCM MENU\n \\main\\covariate model\\BootSCM\n\nThe BootSCM is implemented in PsN. Xpose can import its output and\ngenerate plots similar to those for the BootGAM\n"
pick <- menu(choices, title = title)
qx <- 0
switch(pick + 1, qx <- 2, qx <- 1,
bootscm.import(),
bootgam.print(),
qx <- bootscm.plot.menu()
)
if (qx == 2) {
return(invisible(2))
}
else {
if (qx == 1) {
return(invisible(0))
}
else {
Recall()
}
}
}
| /scratch/gouwar.j/cran-all/cranData/xpose4/R/bootgam.menu.R |
#' Compare parameter estimates for covariate coefficients
#'
#' This function creates a plot of the estimates for covariate coefficients,
#' obtained from the first step (univariate testing) in each scm performed in
#' the bootscm. When normalized for their standard deviation, these plots can
#' be used to compare the strength of the covariate relationship. Coloring is
#' based on the covariate being included in the final model (blue) not being
#' included (red).
#'
#' Optionally, estimated bias is plotted in the graph (as text). Bias is also
#' shown by the difference in mean of parameter estimates when the covariate is
#' included (blue diamond), as opposed to the mean of all parameter estimates
#' (grey diamond)
#'
#' Note: For dichotomous covariates, the default PsN implementation is to use
#' the most common covariate value as base, while the effect of the other
#' value, is estimated by a theta. Xpose (bootscm.import) however recalculates
#' the estimated parameters, to the parametrization in which the lowest value
#' of the dichotomous covariate is the base (e.g. 0), and the estimated THETA
#' denotes the proportional change, when the covariate has the other value
#' (e.g. 1).
#'
#'
#' @param bootgam.obj The object created using bootscm.import(), which hold the
#' data for plotting.
#' @param sd.norm Perform normalization of the covariate coefficients (default
#' is TRUE). When TRUE, the estimated covariate coefficients will be multiplied
#' by the standard deviation of the specific covariate (both for continuous and
#' categorical covariates).
#' @param by.cov.type Split the plot for continuous and dichotomous covariates.
#' Default is FALSE.
#' @param abs.values Show the covariate coefficient in absolute values. Default
#' is FALSE.
#' @param show.data Show the actual covariate coefficients in the plot. Default
#' is TRUE.
#' @param show.means Show the means of included covariates (blue) and all
#' covariates (grey) in the plot. Default is TRUE.
#' @param show.bias Show estimated bias as text in the plot. Default is TRUE.
#' @param dotpch The character used for plotting.
#' @param labels Custom labels for the parameter-covariate relationships,
#' (character vector)
#' @param xlab Custom x-axis label
#' @param ylab Custom y-axis label
#' @param pch.mean The character used for plotting the mean.
#' @param col The color scheme.
#' @param \dots Additional plotting arguments may be passed to this function.
#' @return No value returned.
#' @author Ron Keizer
#' @keywords ~bootscm
#' @examples
#'
#' xp.boot.par.est()
#'
#' @export xp.boot.par.est
xp.boot.par.est <- function (bootgam.obj = NULL,
sd.norm = TRUE,
by.cov.type = FALSE,
abs.values = FALSE,
show.data = TRUE,
show.means = TRUE,
show.bias = TRUE,
dotpch = c(1,19),
labels = NULL,
pch.mean = "|",
xlab = NULL,
ylab = NULL,
col = c(rgb(.8, .5, .5), rgb(.2, .2, .7), rgb(.2,.2,.7), rgb(.6,.6,.6)),
...) {
boot.type <- "bootscm"
bootgam.obj <- get.boot.obj(bootgam.obj, boot.type)
if (is.null(bootgam.obj)) {
return()
}
if (bootgam.obj$group.by.cov == TRUE) {
cat ("This plot cannot be created when imported bootscm results are grouped by covariate.\nPlease re-import the bootscm results.")
return()
}
if (!("par.est.first" %in% names(bootgam.obj))) {
cat ("The required data is not available. Please check that all necessary PsN data was imported.\n")
cat ("Note: If you've used the bootscm.import function, please set 'skip.par.est.import' to FALSE.\n\n")
return(NULL)
}
if (is.null(xlab)) {
xlab <- "Relative parameter estimate (from 1st scm-step)"
}
if (is.null(ylab)) {
ylab <- "Covariate"
}
if (sd.norm == TRUE) {
pl.dat <- bootgam.obj$par.est.long.norm
bias.dat <- bootgam.obj$bias.dat.norm
} else {
pl.dat <- bootgam.obj$par.est.long
bias.dat <- bootgam.obj$bias.dat
}
## order by inclusion frequency
rem <- seq(along = bootgam.obj$results.tab[,1])[bootgam.obj$failed == 1]
cleaned.data <- bootgam.obj$results.tab
if (length(rem)>0) {
cleaned.data <- cleaned.data[-rem,]
}
incl.freq <- apply (cleaned.data, 2, sum)
lev.ord <- names(incl.freq)[order(incl.freq)]
lev.ord <- unlist(sapply(lev.ord,function(x) levels(pl.dat$cov)[grep(x,levels(pl.dat$cov))]),use.names = F)
abs.fun <- function (dat) {return(dat)}
if (abs.values == TRUE) {
abs.fun <- abs
xlab <- paste("Absolute", xlab)
}
if (by.cov.type == TRUE) {
formula <- factor(cov, levels=lev.ord) ~ abs.fun(value) | cov.type
} else {
formula <- factor(cov, levels=lev.ord) ~ abs.fun(value)
}
if (!is.null(labels)) {
labels <- rev(labels)
if (length(labels)==length(lev.ord)) {
idx1 <- match(bias.dat$cov, lev.ord)
idx2 <- match(names(incl.freq), lev.ord)
idx3 <- match(pl.dat$cov, lev.ord)
bias.dat$cov <- labels[idx1]
names(incl.freq) <- labels[idx2]
pl.dat$cov <- labels[idx3]
lev.ord <- names(incl.freq)[order(incl.freq)]
} else {
cat ("Length of specified labels-vector not equal to number of covariate-parameter relationships. Returning to default.")
}
}
legend <- list(text = list("Selected", cex=.75),
points = list(pch=dotpch[2], col=col[3], cex=1),
text = list("Not selected", cex=.75),
points = list(pch=dotpch[1], col=col[1], cex=1) )
if (show.means == TRUE) {
legend <- list(text = list("Selected", cex=.75),
points = list(pch=dotpch[2], col=col[3], cex=1),
text = list("Not selected", cex=.75),
points = list(pch=dotpch[1], col=col[1], cex=1),
text = list("mean (selected)", cex=.75),
lines = list(lwd=1.5, span=0.1, col=col[3]),
text = list("mean (all)", cex=.75),
lines = list(lwd=1.5, span=0.1, col=col[4])
)
}
p <- stripplot (formula,
data = pl.dat,
ylab = ylab,
xlab = xlab,
groups = factor(eval(as.name("incl")), levels = c("Not included", "Included")),
par.settings = simpleTheme (col=col, pch=dotpch),
key = legend,
levels = lev.ord,
panel = function (...) {
panel.abline (v=0, lty=3)
if (show.data == TRUE) {
panel.stripplot (jitter.data=TRUE, ...)
}
if (show.means == TRUE) {
panel.xyplot (y = factor(bias.dat[bias.dat$incl == "Included",]$cov, levels=lev.ord),
x = abs.fun(as.num(bias.dat[bias.dat$incl == "Included",]$mean)),
bias.data=bias.dat, pch = pch.mean, cex=2.5, col=col[3]
)
panel.xyplot (y = factor(bias.dat[bias.dat$incl == "Included",]$cov, levels=lev.ord),
x = abs.fun(as.num(bias.dat[bias.dat$incl == "Included",]$All)),
bias.data=bias.dat, pch = pch.mean, cex=2.5, col=col[4]
)
}
if (show.bias == TRUE) {
panel.text (y = factor(bias.dat[bias.dat$incl=="Included",]$cov, levels=lev.ord),
x = abs.fun(max(pl.dat[!is.na(pl.dat$value),]$value)*0.94),
labels = paste (round(bias.dat[bias.dat$incl=="Included",]$bias,0), "%", sep=""), cex=0.8)
}
}, ...)
return(p)
}
ask.covs.plot <- function (bootgam.obj = NULL) {
if (!is.null(bootgam.obj)) {
cat ("Covariates in database: ")
covs <- colnames(bootgam.obj$covariate$sd.all)
cat (covs)
cat ("\n\nPlot for which covariates (separate by space, return for all): ")
ans <- readline()
if (ans == "") {
return()
}
ans.cov <- strsplit(ans, " ")[[1]]
if (length(ans.cov) < 2) {
cat("Please choose at least 2 covariatess from the list!\n\n")
Recall(bootgam.obj)
} else {
if (sum((ans.cov %in% covs)*1) == length(ans.cov)) {
return (ans.cov)
} else {
cat("Please choose covariates from the list only!\n\n")
Recall(bootgam.obj)
}
}
}
}
#' Correlations between covariate coefficients
#'
#' This function creates a plot showing the correlations in estimates for
#' covariate coefficients, obtained from the first step (univariate testing) in
#' each scm performed in the bootscm.
#'
#'
#' @param bootgam.obj The object created using bootscm.import(), which hold the
#' data for plotting.
#' @param sd.norm Perform normalization of the covariate coefficients (default
#' is TRUE). When TRUE, the estimated covariate coefficients will be multiplied
#' by the standard deviation of the specific covariate (both for continuous and
#' categorical covariates).
#' @param by.cov.type Split the plot for continuous and dichotomous covariates.
#' Default is FALSE.
#' @param cov.plot A character vector which lists the covariates to include in
#' the plot. If none are specified (NULL), all covariate coefficients will be
#' included in the plot.
#' @param ask.covs Ask the user which covariates to include in the plot.
#' Default is FALSE.
#' @param dotpch The character used for plotting.
#' @param col The colors used for plotting.
#' @param \dots Additional plotting arguments may be passed to this function.
#' @return No value returned.
#' @author Ron Keizer
#' @keywords ~bootscm
#' @examples
#'
#' \dontrun{
#' xp.boot.par.est.corr(current.bootscm, sd.norm = TRUE,
#' cov.plot = c("CLSEX", "VSEX", "CLWT"))
#'
#' }
#' @export xp.boot.par.est.corr
xp.boot.par.est.corr <- function (bootgam.obj = NULL,
sd.norm = TRUE,
by.cov.type = FALSE,
cov.plot = NULL, # covariates to plot if not all are wanted
ask.covs = FALSE,
dotpch = 19,
col = rgb(.2, .2, .9, .75),
...) {
boot.type <- "bootscm"
bootgam.obj <- get.boot.obj(bootgam.obj, boot.type)
if (is.null(bootgam.obj)) {
return()
}
if (bootgam.obj$group.by.cov == TRUE) {
cat ("This plot cannot be created when imported bootscm results are grouped by covariate.\nPlease re-import the bootscm results.")
return()
}
if (!("par.est.first" %in% names(bootgam.obj))) {
cat ("The required data is not available. Please check that all necessary PsN data was imported.\n")
cat ("Note: If you've used the bootscm.import function, please set 'skip.par.est.import' to FALSE.\n\n")
return(NULL)
}
tmp <- bootgam.obj$par.est.first
if (sd.norm == TRUE) { # for non-dichotomous covariates, do correction
tmp <- bootgam.obj$par.est.first.corr
xlab <- "Parameter estimate (from 1st scm-step), SD-normalized"
}
pl.dat <- tmp
pl.dat.incl <- (!is.na(bootgam.obj$par.est.final))*1
## filter out the desired covariates
if (is.null(cov.plot)) {
if (ask.covs==TRUE) {
cov.plot <- ask.covs.plot (bootgam.obj)
}
}
if ((!is.null(cov.plot))&&(sum(cov.plot %in% colnames(tmp))>0)) {
pl.dat <- tmp[,cov.plot]
pl.dat.incl <- pl.dat.incl[,cov.plot]
}
p <- splom (pl.dat, pch = dotpch, col=col)
return(p)
}
#' Print summary information for a bootgam or bootscm
#'
#' This functions prints some summary information for a bootgam performed in
#' Xpose, or for a bootscm performed in PsN.
#'
#'
#' @param bootgam.obj The bootgam or bootscm object.
#' @return No value returned
#' @author Ron Keizer
#' @keywords ~bootgam ~bootscm
#' @examples
#'
#' \dontrun{
#' bootgam.print(current.bootgam) # Print summary for the current Xpose bootgam object
#' bootgam.print(current.bootscm) # Print summary for the current Xpose bootscm object
#' }
#'
#' @export bootgam.print
bootgam.print <- function(bootgam.obj = NULL) {
bootgam.obj <- get.boot.obj(bootgam.obj, NULL)
if (is.null(bootgam.obj)) {
return()
}
boot.type <- get.boot.type (bootgam.obj)
cat("\n********************************************************************\n")
if (boot.type == "bootgam") {
cat("************************* BootGAM results **************************\n")
} else {
cat("************************* BootSCM results **************************\n")
}
cat("Run number:", bootgam.obj$runno, "\n")
failed <- NULL
if (boot.type == "bootgam") {
if(is.null(startm <- bootgam.obj$start.mod)) {
cat("No start model specified.\n")
} else {
cat("Start model set to:", startm,"\n")
}
cat("Seed number:", bootgam.obj$seed,"\n")
if(length(bootgam.obj$excluded.ids)>0) {
cat("Excluded individuals:",bootgam.obj$excluded.ids,"\n")
} else {
cat("No individuals were excluded.\n")
}
cat("\nConvergence algorithm:", bootgam.obj$algo,"\n")
if(bootgam.obj$algo == "fluct.ratio") {
cat("Lowest important inclusion frequency:")
cat("\n Convergence criterium:", format(bootgam.obj$fluct.ratio.last, digits = 5), "(target=", bootgam.obj$conv.value, ")\n")
} else {
cat("Lowest absolute joint inclusion frequency:")
cat("\n Convergence criterium:", format(bootgam.obj$ljif.last, digits = 5), "(target=", bootgam.obj$ljif, ")\n")
}
failed <- seq(along=eval(as.name("current.bootgam"))$failed)[eval(as.name("current.bootgam"))$failed==1]
cat ("Failed BootGAM replicates: ", failed, "\n")
}
cat("\nTotal number of iterations:", length(bootgam.obj$results.tab[,1]), "\n")
cat("\nModel size: ")
res <- bootgam.obj$results.tab
if (!is.null(failed)) {
if (length(failed)>0) {
res <- bootgam.obj$results.tab[-failed,]
}
}
print (summary(apply(res, 1, sum)))
cat("\nInclusion probabilities:\n")
tot.prob <- tail(bootgam.obj$incl.freq,1)
ord <- rev(order(tot.prob))
print(t(as.list(round(tot.prob[ord],3))))
cat("********************************************************************\n\n")
}
check.bootgamobj <- function () {
getit <- function() {
cat("\nYou have to specify the parameter name and the run number",
"of the bootgam objects you want to plot. The following",
"bootgam objects are available:\n", fill = 60)
if (.Platform$OS == "windows") {
cat(objects(pattern = "bootgam.xpose*", pos = 1), fill = 60)
}
else {
cat(objects(pattern = "^bootgam.xpose", pos = 1), fill = 60)
}
cat("\nParameter (0 to exit): ")
ans <- readline()
if (ans == 0) {
return(ans <- NULL)
}
cat("Run number (0 to exit):")
ans1 <- readline()
if (ans1 == 0) {
return(ans1 <- NULL)
}
gobjname <- paste("bootgam.xpose.", ans, ".", ans1, sep = "")
if (!exists(gobjname, where = 1)) {
cat("\n*There are no objects that matches", gobjname,
"\n")
gobjname <- Recall()
}
return(gobjname)
}
if (exists("current.bootgam", where = 1)) {
cur.boot <- eval(as.name("current.bootgam"))
cat("\nThe current bootgam object is for", cur.boot$parnam,
"in run", cur.boot$runno, ".\n")
cat("\nDo you want to proceed with this bootgam object? y(n) ")
ans <- readline()
if (ans != "y" && ans != "") {
gobjname <- getit()
if (!is.null(gobjname)) {
c1 <- call("assign",pos = 1, "current.bootgam", eval(as.name(gobjname)),
immediate = T)
eval(c1)
}
} else {
gobjname <- T
}
} else {
gobjname <- getit()
if (!is.null(gobjname)) {
c2 <- call("assign",pos = 1, "current.bootgam", eval(as.name(gobjname)),
immediate = T)
eval(c2)
}
}
return(gobjname)
}
ask.bootgam.bootscm.type <- function () {
cat ("Both a bootgam and a bootscm object are available, which one\nwould you like to summarize?\n")
cat (" 1) the current bootgam object\n")
cat (" 2) the current bootscm object\n")
ans <- readline()
if (ans == "") {
Recall()
} else {
if ((ans == 1)|(ans == 2)) {
if (ans == 1) {return ("bootgam")}
if (ans == 2) {return ("bootscm")}
} else {
cat("Please choose either 1 or 2!\n\n")
Recall()
}
}
}
get.boot.obj <- function (bootgam.obj = NULL,
boot.type = NULL
) {
# switch between supplied object or global object, and bootscm/bootgam
if ((is.null(boot.type))&(is.null(bootgam.obj))) {
if (("current.bootgam" %in% ls(.GlobalEnv))&(!"current.bootscm" %in% ls(.GlobalEnv))) {
boot.type <- "bootgam"
}
if (("current.bootscm" %in% ls(.GlobalEnv))&(!"current.bootgam" %in% ls(.GlobalEnv))) {
boot.type <- "bootscm"
}
if (("current.bootscm" %in% ls(.GlobalEnv))&("current.bootgam" %in% ls(.GlobalEnv))) {
boot.type <- ask.bootgam.bootscm.type()
cat ("\n")
}
if (is.null(boot.type)) {
cat ("No bootgam or bootscm object found!\n")
return()
}
}
if (is.null(boot.type)) {
boot.type <- get.boot.type (bootgam.obj)
}
if (boot.type == "bootscm") {
if (is.null(bootgam.obj)) {
if ("current.bootscm" %in% objects(pos=1)) {
if (!is.null(eval(as.name("current.bootscm")))) {
bootgam.obj <- eval(as.name("current.bootscm"))
} else {
cat ("Data not available. Did you import the bootSCM data?\n")
}
} else {
cat (paste(objects()))
cat ("Data not available. Did you import the bootSCM data?\n")
}
} else {
c3 <- call("assign",pos = 1, "current.bootscm", bootgam.obj, immediate = T)
eval(c3)
}
} else { # load bootgam object
if (is.null(bootgam.obj)) {
if ("current.bootgam" %in% objects()) {
if (!is.null(bootgam.obj)) {
bootgam.obj <- eval(as.name("current.bootgam"))
}
} else {
if (check.bootgamobj()) {
bootgam.obj <- eval(as.name("current.bootgam"))
} else {
cat ("Data not available. Did you run the bootGAM data?\n")
}
}
} else {
c4 <- call("assign",pos = 1, "current.bootgam", bootgam.obj, immediate = T)
eval(c4)
}
}
return(bootgam.obj)
}
#' Plot of model size distribution for a bootgam or bootscm
#'
#' This function creates a kernel smoothed plot of the number of covariates
#' included in the final model in each gam/scm in the bootgam/bootscm
#' procedure.
#'
#'
#' @param bootgam.obj The bootgam or bootscm object.
#' @param boot.type Either "bootgam" or "bootscm". Default is NULL, which means
#' the user will be asked to make a choice.
#' @param main Plot title.
#' @param bw The smoothing bandwidth to be used for the kernel.
#' @param xlb The x-axis label.
#' @param \dots Additional plotting parameter may be passed to this function.
#' @return A lattice plot object will be returned.
#' @author Ron Keizer
#' @keywords ~bootgam ~bootscm
#' @export xp.distr.mod.size
xp.distr.mod.size <- function (bootgam.obj = NULL,
boot.type = NULL,
main = NULL,
bw = 0.5,
xlb = NULL,
... ) {
bootgam.obj <- get.boot.obj(bootgam.obj, boot.type)
if (is.null(bootgam.obj)) {
return()
}
boot.type <- get.boot.type (bootgam.obj)
## Sort out the titles
if(is.null(main)) {
main <- paste("Distribution of covariate model sizes", bootgam.obj$runno)
}
if (is.null(xlb)) {
if (boot.type == "bootgam") {
xlb <- paste ("Covariate model size (on", bootgam.obj$parnam, ")", sep = "")
} else {
xlb <- paste ("Covariate model size (on any parameter)")
}
}
# Plot
res <- bootgam.obj$results.tab
if (!is.null(bootgam.obj$failed)) {
res <- res[bootgam.obj$failed == 0,]
}
sizes <- apply (res, 1, sum)
pl <- densityplot (sizes,
bw = bw,
main = main,
... )
return(pl)
}
ask.incl.range <- function (bootgam.obj = NULL) {
text <- paste("The plots that show correlations between covariate inclusion\n",
"frequencies (inclusion index) are not informative when the inclusion\n",
"frequency for a covariate is either very high or very low. Therefore\n",
"it is advised to show these plots only for intermediately strong \n",
"covariates. The default range is 20% to 80%.\n\n", sep="")
cat (text)
cat ("Specify range (e.g.: 20 80): ")
ans <- readline()
if (ans == "") {
range <- c(20,80)
} else {
range <- as.numeric(strsplit (ans, " ")[[1]])
}
if (length(range) == 2) {
return (range)
} else {
cat("Please specify two numbers, separated by a space!\n\n")
Recall(bootgam.obj)
}
}
#' Plot of inclusion index of covariates.
#'
#' Covariate inclusion indices show the correlation in inclusion of a covariate
#' in the final model in a bootgam or bootscm.
#'
#' @param bootgam.obj The bootgam or bootscm object.
#' @param boot.type Either "bootgam" or "bootscm". Default is NULL, which means
#' the user will be asked to make a choice.
#' @param main Plot title.
#' @param xlb Label for the x-axis.
#' @param ylb Label for the y-axis.
#' @param add.ci Add a confidence interval to the plotted data.
#' @param incl.range Included range
#' @param return_plot Should the function return a plot?
#' @param results.tab Specify your own results table.
#' @param ... Additional plotting information.
#'
#' @return A lattice plot object is returned.
#' @author Ron Keizer
#' @export
#'
#' @family bootgam
#' @family bootscm
xp.incl.index.cov <- function (
bootgam.obj = NULL,
boot.type = NULL,
main = NULL,
xlb = "Index",
ylb = "Covariate",
add.ci = FALSE,
incl.range = NULL,
return_plot = TRUE,
results.tab = NULL,
...) {
bootgam.obj <- get.boot.obj(bootgam.obj, boot.type)
if (is.null(bootgam.obj)) {
return()
}
boot.type <- get.boot.type(bootgam.obj)
as.num <- function(dat) {
return(as.numeric(as.character(dat)))
}
if (is.null(main)) {
main <- paste("Inclusion index for", bootgam.obj$runno)
}
se_idx <- function(p, q, n) {
A <- (p/n) * (1 - (p/n))/n
B <- (q/n) * (1 - (q/n))/n
rho <- 1
se <- sqrt(A + B + 2 * sqrt(A) * sqrt(B) * rho)
return(se)
}
inc_obs <- tail(bootgam.obj$incl.freq, 1)
if(!is.null(results.tab)) {
res <- results.tab
} else {
res <- bootgam.obj$results.tab
}
if (is.null(incl.range)) {
incl.range <- ask.incl.range()
}
if (length(incl.range) == 2) {
filter <- inc_obs > incl.range[1]/100 & inc_obs < incl.range[2]/100
res <- res[, filter]
inc_obs <- inc_obs[, filter]
}
n_cov <- length(inc_obs)
nam <- names(inc_obs)
if (!is.null(bootgam.obj$failed)) {
res <- res[bootgam.obj$failed == 0, ]
}
if (boot.type == "bootscm") {
cols.dum <- grep("^X.", colnames(res))
if (length(cols.dum) > 0) {
res <- res[, -cols.dum]
}
}
cov_idx <- c()
n <- length(res[, 1])
for (i in 1:n_cov) {
sub <- res[res[, i] == 1, ]
obs <- apply(sub, 2, sum)
expect <- inc_obs * n
idx <- as.num((obs/n)) - (as.num(inc_obs[i])*as.num(inc_obs))
idx[i] <- NA
se <- 0
# RK: removed for now, not correct and problably not useful
# if (add.ci == TRUE) {
# se <- unlist(se_idx(p = obs, q = expect, n = length(res[, 1])))
# }
cov_idx <- data.frame(rbind(cov_idx, cbind(COV1 = nam[i],
COV2 = nam, idx, se, lbnd = (idx - (1.96 * se)),
ubnd = (idx + (1.96 * se)))))
}
if(return_plot) {
p <- dotplot(as.factor(COV1) ~ as.num(idx) | as.factor(COV2),
data = cov_idx, plot.zero = TRUE, main = main, xlab = xlb,
ylab = ylb, lx = as.num(cov_idx$lbnd), ux = as.num(cov_idx$ubnd),
prepanel = prepanel.ci,
panel = panel.ci,
...)
} else {
return(cov_idx)
}
return(p)
}
ask.cov.name <- function (bootgam.obj = NULL) {
if (!is.null(bootgam.obj)) {
cat ("Covariates in database: ")
cat (paste (bootgam.obj$covnams))
cat ("\n\nPlot for which covariate (return to exit): ")
ans <- readline()
if (ans == "") {
return()
}
if (ans %in% (bootgam.obj$covnams)) {
return (ans)
} else {
cat("Please choose a covariate from the list!\n\n")
Recall(bootgam.obj)
}
}
}
#' Individual inclusion index
#'
#' This function will generate a plot of individual inclusion indexes for a
#' specific covariate, which can be used to identify influential
#' individuals for inclusion of that covariate. The index for an individual is calculated as
#' the observed number of inclusions of that individual when the specific
#' covariate was included minus the expected number of inclusions (based
#' on the total bootstrap inclusions), divided by expected.
#'
#' @param bootgam.obj A bootgam or bootscm object.
#' @param boot.type Either "bootgam" or "bootscm". Default is NULL, which means the user
#' will be asked to make a choice.
#' @param cov.name The name of the covariate for which to create the plot.
#' @param main The title of the plot.
#' @param ylb The label for the x-axis.
#' @param xlb The label for the y-axis.
#' @param return_plot Should a plot object be returned?
#' @param results.tab Supply your own results table.
#' @param ... Additional plotting parameters.
#'
#' @return A lattice plot object is returned.
#' @author Ron Keizer
#' @export
#'
#' @family bootgam
#' @family bootscm
# @examples
xp.incl.index.cov.ind <- function (bootgam.obj = NULL,
boot.type = NULL,
cov.name = NULL,
main = NULL,
ylb = "ID",
xlb = "Individual inclusion index",
return_plot = TRUE,
results.tab = NULL,
... ) {
bootgam.obj <- get.boot.obj(bootgam.obj, boot.type)
if (is.null(bootgam.obj)) {
return()
}
boot.type <- get.boot.type (bootgam.obj)
as.num <- function (dat) { return (as.numeric(as.character(dat))) }
if (is.null(cov.name)) {
cov.name <- ask.cov.name(bootgam.obj)
}
if (is.null(cov.name)) { return() }
if(is.null(main)) {
main <- paste ("Individual inclusion index (", cov.name, " on ", bootgam.obj$parnam, ") for ", bootgam.obj$runno, sep="")
}
if(!is.null(results.tab)) {
res <- results.tab
bootgam.obj$oid <- bootgam.obj$oid[1:length(results.tab[,1]),]
} else {
res <- bootgam.obj$results.tab
}
ids <- colnames(bootgam.obj$oid)
oid.cnt <- apply (bootgam.obj$oid, 2, sum)
if (!is.null(bootgam.obj$failed)) {
res <- res[bootgam.obj$failed == 0,]
}
oid.rel <- oid.cnt / length(res[,1])
nam <- names(res)
cov_idx <- c()
sub <- bootgam.obj$oid[res[, cov.name == nam]==1,]
obs <- apply (sub, 2, sum)
n <- length(sub[,1])
idx <- (as.num(obs) / (n * as.num(oid.rel))) - 1
ord <- order(idx)
ids <- as.num(gsub("X","", ids))
cov_idx <- data.frame(cbind ("idn" = ids[ord], "idx" = as.num(idx[ord])))
scales <- list(y = list (labels = rev(cov_idx$idn)), cex=c(0.7,1))
if(return_plot) {
p <- xyplot (factor(idn, levels=rev(idn)) ~ as.num(idx),
data = cov_idx,
main = main,
xlab = xlb,
ylab = ylb,
scales = scales,
lx = 0, ux = 0, plot.zero=TRUE,
prepanel = prepanel.ci,
panel = panel.ci,
... )
return (p)
} else {
return(cov_idx)
}
}
#' Inclusion index individuals, compare between covariates.
#'
#' A plot showing the range of inclusion indices for individuals for all
#' covariates. This plot can be used to evaluate whether there were covariates
#' which were more influenced by the constituency of the bootstrapped dataset
#' than others.
#'
#'
#' @param bootgam.obj A bootgam or bootscm object.
#' @param boot.type Either "bootgam" or "bootscm". Default is NULL, which means
#' the user will be asked to make a choice.
#' @param main The title of the plot.
#' @param xlb The label for the x-axis.
#' @param ylb The label for the y-axis.
#' @param \dots Additional plotting parameters.
#' @return A lattice plot object is returned.
#' @author Ron Keizer
#' @keywords ~bootgam ~bootscm
#' @export xp.incl.index.cov.comp
xp.incl.index.cov.comp <- function (bootgam.obj = NULL,
boot.type = NULL,
main = NULL,
xlb = "Individual inclusion index",
ylb = "ID",
... ) {
bootgam.obj <- get.boot.obj(bootgam.obj, boot.type)
if (is.null(bootgam.obj)) {
return()
}
as.num <- function (dat) { return (as.numeric(as.character(dat))) }
boot.type <- get.boot.type (bootgam.obj)
if(is.null(main)) {
main <- paste ("Individual inclusion indices for", bootgam.obj$runno)
}
ids <- colnames(bootgam.obj$oid)
oid.cnt <- apply (bootgam.obj$oid, 2, sum)
res <- bootgam.obj$results.tab
if (!is.null(bootgam.obj$failed)) {
res <- res[bootgam.obj$failed == 0,]
}
oid.rel <- oid.cnt / length(res[,1])
nam <- names(res)
cov_idx <- c()
for (i in seq(along=nam)) {
sub <- bootgam.obj$oid[res[,nam[i] == nam]==1,]
obs <- apply (sub, 2, sum)
n <- length(sub[,1])
idx <- (as.num(obs) / (n * as.num(oid.rel))) - 1
cov_idx <- data.frame(rbind (cov_idx, cbind ("cov" = nam[i], "idx" = as.num(idx))))
}
p <- xyplot (factor(cov) ~ as.num(idx),
data=cov_idx,
xlab = xlb,
ylab = ylb,
main = main,
lx = 0, ux = 0,
plot.zero = TRUE,
prepanel = prepanel.ci,
panel = panel.ci,
... )
return (p)
}
#' Inclusion frequency plot
#'
#' Plot the inclusion frequencies of covariates in the final models obtained in
#' a bootgam or bootscm. Covariates are ordered by inclusion frequency.
#'
#'
#' @param bootgam.obj The bootgam or bootscm object.
#' @param boot.type Either "bootgam" or "bootscm". Default is NULL, which means
#' the user will be asked to make a choice.
#' @param main Plot title
#' @param col Color used for the plot.
#' @param xlb Label for x-axis.
#' @param ylb Label for y-axis.
#' @param \dots Additional plotting parameters.
#' @return A lattice plot object will be returned.
#' @author Ron Keizer
#' @keywords ~bootgam ~bootscm
#' @export xp.inc.prob
xp.inc.prob <- function (bootgam.obj = NULL,
boot.type = NULL,
main = NULL,
col = "#6495ED",
xlb = NULL,
ylb = "Covariate",
... ) {
bootgam.obj <- get.boot.obj(bootgam.obj, boot.type)
if (is.null(bootgam.obj)) {
return()
}
boot.type <- get.boot.type (bootgam.obj)
## Sort out the titles
if(is.null(main)) {
main <- paste("Total frequency of covariates for", bootgam.obj$runno)
}
rem <- seq(along = bootgam.obj$results.tab[,1])[bootgam.obj$failed == 1]
cleaned.data <- bootgam.obj$results.tab
if (length(rem)>0) {
cleaned.data <- bootgam.obj$results.tab[-rem,]
}
frac <- function (data) { sum (data) / length(data) }
se <- function (data) {
p <- sum (data) / length(data)
se <- p * (1-p) / length(data)
return (se)
}
as.num <- function (data) { return (as.numeric(as.character(data)))}
cov.prob <- apply (cleaned.data, 2, frac)
cov.prob <- cov.prob[order(cov.prob)]
cov.se <- apply (cleaned.data, 2, se)
cov.se <- cov.se[order(cov.prob)]
cov.ci <- cbind ("ubnd" = cov.prob + 1.96*cov.se, "lbnd" = cov.prob - 1.96*cov.se)
cov.comb <- data.frame ( cbind ( "cov" = names(cov.prob), "prob" = cov.prob, cov.ci) )
cov.comb <- cov.comb[order(cov.comb$prob),]
if (is.null(xlb)) {
xlb <- paste("Inclusion frequency (%) on ", bootgam.obj$parnam, sep="")
if (boot.type == "bootscm") {
xlb <- "Inclusion frequency (%)"
}
}
pl <- xyplot (factor(cov, levels=cov) ~ 100*as.num(prob),
lx = as.num(cov.comb$lbnd), ux = as.num(cov.comb$ubnd),
data = cov.comb,
prepanel = prepanel.ci,
panel = panel.ci,
main = main,
xlim = c(0,100),
xlab = xlb,
ylab = ylb,
... )
return(pl)
}
#' Inclusion frequency plot for combination of covariates.
#'
#' Plot the inclusion frequency of the most common 2-covariate combinations.
#'
#'
#' @param bootgam.obj The bootgam or bootscm object.
#' @param boot.type Either "bootgam" or "bootscm". Default is NULL, which means
#' the user will be asked to make a choice.
#' @param main Plot title
#' @param col Color used for plot.
#' @param xlb Label for x-axis.
#' @param ylb Label for y-axis.
#' @param \dots Additional plotting parameters.
#' @return A lattice plot object will be returned.
#' @author Ron Keizer
#' @keywords ~bootgam ~bootscm
#' @export xp.inc.prob.comb.2
xp.inc.prob.comb.2 <- function (bootgam.obj = NULL,
boot.type = NULL,
main = NULL,
col = "#6495ED",
xlb = NULL,
ylb = "Covariate combination",
... ) {
bootgam.obj <- get.boot.obj(bootgam.obj, boot.type)
if (is.null(bootgam.obj)) {
return()
}
if(is.null(main)) {
main <- paste("Most common 2-covariate combinations for", bootgam.obj$runno)
}
boot.type <- get.boot.type (bootgam.obj)
rem <- seq(along = bootgam.obj$results.tab[,1])[bootgam.obj$failed == 1]
cleaned.data <- bootgam.obj$results.tab
if (length(rem) > 0) {
cleaned.data <- cleaned.data[-rem,]
}
frac <- function (data) { sum (data) / length(data) }
se <- function (data) {
p <- sum (data) / length(data)
se <- p * (1-p) / length(data)
return (se)
}
as.num <- function (data) { return (as.numeric(as.character(data)))}
covs <- colnames(cleaned.data)
cov_all <- c()
for (i in seq(along=covs)) {
tmp <- cleaned.data[cleaned.data[,i] == 1, -i]
cov.prob <- apply (tmp, 2, frac)
cov_all <- data.frame (rbind (cov_all, cbind ("cov1"=covs[i], "cov2" = names(cov.prob), "idx" = as.num(cov.prob))))
}
cov_all$idx <- as.num(cov_all$idx)
cov_all_10 <- head(cov_all[order(cov_all$idx, decreasing=TRUE),], 10)
cov_all_10$label <- paste(cov_all_10$cov1, "+", cov_all_10$cov2)
if (is.null(xlb)) {
xlb <- paste("Inclusion frequency (%) on ", bootgam.obj$parnam, sep="")
if (boot.type == "bootscm") {
xlb <- "Inclusion frequency (%) on any parameter)"
}
}
pl <- dotplot (factor(label, levels=rev(cov_all_10$label)) ~ 100*as.num(idx),
lx = 0, ux=0,
data = cov_all_10,
prepanel = prepanel.ci,
panel = panel.ci,
xlim = c(0,100),
main = main,
xlab = xlb,
ylab = ylb,
...)
return(pl)
}
prepanel.ci <- function(x, y, lx, ux, subscripts, ...) {
x <- as.numeric(x)
lx <- as.numeric(lx[subscripts])
ux <- as.numeric(ux[subscripts])
list(xlim = range(x, ux, lx, finite = TRUE))
}
panel.ci <- function(x, y, lx, ux, subscripts, pch = 16, plot.zero = FALSE, ...) {
x <- as.numeric(x)
y <- as.numeric(y)
lx <- as.numeric(lx[subscripts])
ux <- as.numeric(ux[subscripts])
if (plot.zero == TRUE) {
panel.abline (v = 0, lty = 3, lwd = 1, col="#999999")
}
panel.abline(h = unique(y), col = "grey", lwd = 1)
# show SE of estimate. Disabled.
# panel.arrows(lx, y, ux, y, col = 'black', lwd = 2,
# length = 0, unit = "native",
# angle = 90, code = 3)
panel.xyplot(x, y, pch = pch, ...)
}
#' Inclusion stability plot
#'
#' A plot of the inclusion frequency of covariates vs bootgam/bootscm
#' iteration number. This plot can be used to evaluate whether sufficient
#' iterations have been performed.
#'
#' @param bootgam.obj The bootgam or bootscm object.
#' @param boot.type Either "bootgam" or "bootscm". Default is NULL,
#' which means the user will be asked to make a choice.
#' @param main Plot title
#' @param normalize Should the plot be normalized?
#' @param split.plots Should the plots be split?
#' @param xlb The label for the x-axis.
#' @param ylb The label for the y-axis.
#' @param ... Additional plotting parameters
#'
#' @return A lattice plot object is returned.
#' @author Ron Keizer
#' @export
#'
#' @family bootgam
#' @family bootscm
#'
# @examples
xp.inc.stab.cov <- function (bootgam.obj = NULL,
boot.type = NULL,
main = NULL,
normalize = TRUE,
split.plots = FALSE,
xlb = "Bootstrap replicate number",
ylb = "Difference of estimate with final",
...) {
var <- NULL
## Create a plot of d(inclusion frequency-final inclusion freq) versus bootstrap replicate number (x)
bootgam.obj <- get.boot.obj(bootgam.obj, boot.type)
if (is.null(bootgam.obj)) {
return()
}
boot.type <- get.boot.type (bootgam.obj)
if(is.null(main) && !is.null(bootgam.obj$runno) && bootgam.obj$runno != "") {
main <- paste("Inclusion stability for", bootgam.obj$runno)
}
freq <- bootgam.obj$incl.freq
if(normalize) {
freq <- apply(bootgam.obj$incl.freq, 2, function(x) { x - tail(x,1) } )
}
if (!is.null(bootgam.obj$failed)) {
freq <- freq[bootgam.obj$failed==0,]
}
freq <- data.frame (cbind (row = seq(along = freq[,1]), freq))
freq.long <- reshape (freq,
ids=row.names(freq), varying = names(freq)[-1],
idvar = "row", timevar = "var", v.names = "value",
times = names(freq)[-1], direction="long")
if(split.plots) {
pl <- xyplot (value ~ row | var,
data = freq.long,
main = main,
xlab = xlb,
ylab = ylb,
type = "l",
panel=function(...) {
panel.abline(h = 0, col="#888888")
panel.xyplot(...)
},
...)
} else {
pl <- xyplot (value ~ row,
groups = var,
col = rgb(0.4, 0.4, 0.4, 0.7),
data = freq.long,
main = main,
xlab = xlb,
ylab = ylb,
type = "l",
panel=function(...) {
panel.abline(h = 0, col='steelblue', lwd=2)
panel.xyplot(...)
},
...)
}
return (pl)
}
#' OFV difference (optimism) plot.
#'
#' A plot of the difference in OFV between final bootscm models and the
#' reference final scm model.
#'
#'
#' @param bootscm.obj The bootgam or bootscm object.
#' @param main Plot title.
#' @param xlb Label for x-axis.
#' @param ylb Label for y-axis.
#' @param \dots Additional plotting parameters.
#' @return A lattice plot object is returned.
#' @author Ron Keizer
#' @keywords ~bootgam ~bootscm
#' @export xp.dofv.plot
xp.dofv.plot <- function (bootscm.obj = NULL,
main = NULL,
xlb = "Difference in OFV",
ylb = "Density",
... ) {
bootscm.obj <- get.boot.obj(bootscm.obj, boot.type = "bootscm")
if (is.null(bootscm.obj)) {
return()
}
## Sort out the titles
if(is.null(main)) {
main <- paste("Distribution of dOFV for", bootscm.obj$runno)
}
# Plot
dofv <- bootscm.obj$dofv[!is.na(bootscm.obj$dofv$dOFV),]$dOFV
dofv <- dofv[-1]
pl <- densityplot (dofv, lwd=3,
main=main,
xlab = xlb,
ylab = ylb,
panel = function () {
panel.abline (v=0, lty=3, col="#888888")
panel.densityplot (dofv)
},
... )
return (pl)
}
get.boot.type <- function (bootscm.obj) {
boot.type <- "bootgam"
if ("dofv" %in% names(bootscm.obj)) {
boot.type <- "bootscm"
}
return(boot.type)
}
#' Trace plots for conditional indices
#'
#' @inheritParams xp.dofv.npar.plot
#' @inheritParams xp.inc.stab.cov
#' @param boot.type Either "bootgam" or "bootscm". Default is NULL, which means
#' the user will be asked to make a choice.
#' @param normalize Should one normalize?
#' @param split.plots Should the plots be split?
#'
#' @return A lattice plot object.
#' @export
#'
#' @family bootgam
#' @family bootscm
# @examples
xp.inc.cond.stab.cov <- function (
## trace plots for conditional indices
bootgam.obj = NULL,
boot.type = NULL,
main = NULL,
xlb = "Bootstrap replicate number",
ylb = "Conditional inclusion frequency",
normalize = TRUE,
split.plots = FALSE,
...) {
label <- NULL
var <- NULL
bootgam.obj <- get.boot.obj(bootgam.obj, boot.type)
if (is.null(bootgam.obj)) {
return()
}
boot.type <- get.boot.type(bootgam.obj)
if (is.null(main) && !is.null(bootgam.obj$runno) && bootgam.obj != "") {
main <- paste("Conditional index stability for", bootgam.obj$runno)
}
## get inclusion frequency from bootscm object
res <- c()
for(i in 1:length(bootgam.obj$incl.freq[,1])) {
tmp <- xp.incl.index.cov(bootgam.obj = bootgam.obj, return_plot = FALSE, results.tab = bootgam.obj$results.tab[1:i,], incl.range = c(20,80))
tmp <- tmp[tmp$COV1 != tmp$COV2,]
res <- rbind(res, cbind(i, as.character(tmp$COV1), as.character(tmp$COV2), as.numeric(as.character(tmp$idx))))
}
res <- data.frame(res)
colnames(res) <- c("id", "COV1", "COV2", "value")
res$id <- as.numeric(as.character(res$id))
res$value <- as.numeric(as.character(res$value))
res$label <- paste0(res$COV1, "-", res$COV2)
if(normalize) {
unq <- unique(res$label)
lst <- res[res$id == max(res$id),]
for(i in seq(unique(res$label))) {
res[res$label == unq[i],]$value <- res[res$label == unq[i],]$value - lst[lst$label == unq[i],]$value
}
}
if(split.plots) {
pl <- xyplot(value ~ id | factor(label), data = res, main = main,
xlab = xlb, ylab = ylb, type = "l",
panel=function(...) {
panel.abline(h = 0, col="#888888")
panel.xyplot(...)
}, ...)
} else {
pl <- xyplot(value ~ id, data = res, main = main,
groups = label,
col = rgb(0.4, 0.4, 0.4, 0.5),
panel=function(...) {
panel.abline(h = 0, col='steelblue', lwd=2)
panel.xyplot(...)
},
xlab = xlb, ylab = ylb, type = "l", ...)
}
return(pl)
}
#' Trace plots for conditional indices rper replicate number
#'
#' @inheritParams xp.dofv.npar.plot
#' @inheritParams xp.inc.cond.stab.cov
#' @inheritParams xp.inc.stab.cov
#'
#' @param limits Limits for the inclusion index.
#' @param start When to start.
#' @param ... Arguments passed to other functions.
#'
#' @return A lattice plot object.
#' @export
#'
#' @family bootgam
#' @family bootscm
# @examples
xp.inc.ind.cond.stab.cov <- function (
## trace plots for conditional indices
bootgam.obj = NULL,
boot.type = NULL,
main = NULL,
xlb = "Bootstrap replicate number",
ylb = "Conditional inclusion frequency",
limits = c(.2, .8),
normalize = TRUE,
split.plots = FALSE,
start = 25,
...) {
label <- NULL
idn <- NULL
bootgam.obj <- get.boot.obj(bootgam.obj, boot.type)
if (is.null(bootgam.obj)) {
return()
}
boot.type <- get.boot.type(bootgam.obj)
if (is.null(main) && !is.null(bootgam.obj$runno) && bootgam.obj != "") {
main <- paste("Conditional index stability for", bootgam.obj$runno)
}
## get inclusion frequency from bootscm object
res <- c()
# get list of covariate names that have 20-80% inclusion index
sel <- c(tail(bootgam.obj$incl.freq,1) > limits[1] & tail(bootgam.obj$incl.freq,1) < limits[2])
cov_list <- names(bootgam.obj$incl.freq[sel])
message("Calculating conditional inclusion indices per bootstrap iteration...")
pb <- txtProgressBar(min = 0, max = length(bootgam.obj$incl.freq[,1]), initial = 0)
res <- c()
for(i in start:length(bootgam.obj$incl.freq[,1])) {
setTxtProgressBar(pb, i)
dat_i <- c()
for(j in seq(cov_list)) {
tmp <- xp.incl.index.cov.ind(bootgam.obj = bootgam.obj,
return_plot = FALSE,
results.tab = bootgam.obj$results.tab[1:i,],
cov.name = cov_list[j])
tmp <- tmp[order(tmp$idn),]
if(j == 1) {
dat_i <- tmp
colnames(dat_i)[2] <- cov_list[j]
} else {
dat_i[[cov_list[j]]] <- tmp$idx
}
}
res <- rbind(res, dat_i) # can be implemented faster!
}
res <- data.frame(res)
res$n <- rep(start:length(bootgam.obj$incl.freq[,1]), each = length(dat_i[,1]))
res.long <- reshape (res,
ids=row.names(res), varying = names(res)[-c(1, length(res[1,]))],
idvar = "row", timevar = "var", v.names = "value",
times = names(res)[-c(1, length(res[1,]))], direction="long")
res.long$label <- paste0(res.long$var, "_", res.long$idn)
if(normalize) {
message("Normalizing...")
pb2 <- txtProgressBar(min = 0, max = length(unique(res.long$label)), initial = 0)
unq <- unique(res.long$label)
lst <- res.long[res.long$n == max(res$n),]
for(i in seq(unique(res.long$label))) {
setTxtProgressBar(pb2, i)
res.long[res.long$label == unq[i],]$value <- res.long[res.long$label == unq[i],]$value - lst[lst$label == unq[i],]$value
}
}
message("Plotting...")
if(split.plots) {
pl <- xyplot(value ~ n | var, data = res.long, main = main,
group = idn, col = "#888888",
xlab = xlb, ylab = ylb, type = "l",
panel=function(...) {
panel.abline(h = 0, col="steelblue")
panel.xyplot(...)
}, ...)
} else {
pl <- xyplot(value ~ n, data = res.long, main = main,
groups = label,
col = rgb(0.4, 0.4, 0.4, 0.25),
panel=function(...) {
panel.abline(h = 0, col='steelblue', lwd=2)
panel.xyplot(...)
},
xlab = xlb, ylab = ylb, type = "l", ...)
}
return(pl)
}
#' Distribution of difference in OFV
#'
#' @param bootscm.obj a bootscm object.
#' @param main The title of the plot
#' @param xlb The x-label of the plot
#' @param ylb The y-label of the plot
#' @param ... Additional parameters passed to \code{panel.xyplot} and \code{xyplot}.
#'
#' @return A lattice plot object.
#' @export
#'
#' @family bootgam
#' @family bootscm
#'
# @examples
xp.dofv.npar.plot <- function (bootscm.obj = NULL, main = NULL, xlb = "Difference in OFV",
ylb = "Density", ...) {
bootscm.obj <- get.boot.obj(bootscm.obj, boot.type = "bootscm")
if (is.null(bootscm.obj)) {
return()
}
if (is.null(main)) {
main <- paste("Distribution of dOFV for", bootscm.obj$runno)
}
size <- as.numeric(apply(cbind(bootscm.obj$results.tab, bootscm.obj$results.tab.dum), 1, "sum"))
size_orig <- sum(bootscm.obj$results.tab.orig)
dofv <- bootscm.obj$dofv$dOFV[-1]
ofv <- bootscm.obj$dofv$OFV[-1]
ofv_original <- bootscm.obj$ofv_original
data <- data.frame(cbind(n = 1:length(size), size, dofv, ofv, ofv_original))
data$class <- 0
chi <- data.frame(cbind(x = c(-4, -3, -2, -1, 0, 1, 2, 3, 4) + size_orig,
y = c(qchisq(p = 0.95, df = c(4, 3, 2, 1)), 0, -qchisq(p = 0.95, df = c(1, 2, 3, 4))) ))
data$class <- as.numeric(data$dofv <= chi$y[match(data$size, chi$x)])
bg <- c(rgb(0.5,0.5,0.5,0.5), "darkblue")
sz <- c(1, 1)
font_sz <- c(0.5, .75)
font_col <- c(rgb(1,1,1,0), "white")
message("Models with largest dOFV:")
print(data[order(data$dofv),][1:10,])
pl <- xyplot(dofv ~ size, data=data,
ylab = "dOFV",
xlab = "Covariate model size",
pch = 19,
panel = function(...) {
llines (x=chi$x, y=chi$y)
panel.abline(h = 0, lty = "dotted", col = "black")
panel.abline(v = size_orig, lty = "dotted", col = "black")
panel.xyplot(..., cex = sz[data$class+1], col=bg[data$class+1])
# panel.text(size, dofv, labels = data$n, cex=font_sz[data$class+1], col=font_col[data$class+1])
}, ...)
return(pl)
}
#' Distribution of difference in AIC
#'
#' @param bootscm.obj a bootscm object.
#' @param main The title of the plot
#' @param xlb The x-label of the plot
#' @param ylb The y-label of the plot
#' @param ... Additional parameters passed to \code{panel.xyplot} and \code{xyplot}.
#'
#' @return A lattice plot object.
#' @export
#'
#' @family bootgam
#' @family bootscm
# @examples
xp.daic.npar.plot <- function (bootscm.obj = NULL, main = NULL, xlb = "Difference in AIC",
ylb = "Density", ...) {
bootscm.obj <- get.boot.obj(bootscm.obj, boot.type = "bootscm")
if (is.null(bootscm.obj)) {
return()
}
if (is.null(main)) {
main <- paste("Distribution of dAIC for", bootscm.obj$runno)
}
size <- as.numeric(apply(cbind(bootscm.obj$results.tab, bootscm.obj$results.tab.dum), 1, "sum"))
size_orig <- sum(bootscm.obj$results.tab.orig)
dofv <- bootscm.obj$dofv$dOFV[-1]
ofv <- bootscm.obj$dofv$OFV[-1]
ofv_original <- bootscm.obj$ofv_original
data <- data.frame(cbind(n = 1:length(size), size, size_orig, ofv, dofv, ofv_original, class = 0))
# AIC = 2k - 2log(L)
# dAIC = 2k1 * log(L1) - 2k2 * log(L2)
data$daic <- (2 * data$size + data$ofv) - (2 * data$size_orig + data$ofv_original)
data$class <- as.numeric(data$daic <= 0)
bg <- c(rgb(0.5,0.5,0.5,0.5), "darkblue")
sz <- c(1, 1)
font_sz <- c(0.5, .75)
font_col <- c(rgb(1,1,1,0), "white")
message("Models with largest dAIC:")
print(data[order(data$daic),][1:20,])
pl <- xyplot(daic ~ size, data=data,
ylab = "dAIC", xlab = "Covariate model size",
pch = 19,
panel = function(...) {
panel.abline(h = 0, lty = "dotted", col = "black")
panel.abline(v = size_orig, lty = "dotted", col = "black")
panel.xyplot(..., cex = sz[data$class+1], col=bg[data$class+1])
# panel.text(data$size, data$daic, labels = data$n, cex=font_sz[data$class+1], col=font_col[data$class+1])
}, ...)
return(pl)
}
| /scratch/gouwar.j/cran-all/cranData/xpose4/R/bootgam.plots.R |
#' Import bootscm data into R/Xpose
#'
#' This function imports data generated by the PsN boot_scm function into the
#' Xpose / R environment.
#'
#'
#' @param scm.folder The folder in which the PsN-generated bootscm data are.
#' @param silent Don't output any progress report. Default is FALSE.
#' @param n.bs The number of bootstraps performed. Defaults to 100.
#' @param cov.recoding For categorical covariates that are recoded to
#' dichotomous covariates within the bootscm configuration file, a list can be
#' specified containing data frames for recoding. See the example below for
#' details.
#' @param group.by.cov Group inclusion frequencies by covariate, instead of
#' calculating them per parameter-covariates relationship. Default is NULL,
#' which means that the user will be asked to make a choice.
#' @param skip.par.est.import Skip the import of all parameter estimates (in
#' each final model in all scm's, as well as parameter estimates in first step
#' of each scm). These data are required to make plot that show inclusion bias
#' and correlation in parameter estimates. Importing these data takes a bit of
#' time (may take a minute or so), so if you don't intend to make these plots
#' anyhow this step can be skipped. Default is FALSE.
#' @param runno The run-number of the base model for this bootSCM.
#' @param dofv.forward dOFV value used in forward step of scm.
#' @param dofv.backward dOFV value used in backward step of scm.
#' @param return.obj Should the bootscm object be returned by the function?
#' @author Ron Keizer
#' @family bootscm
#' @export
#' @family PsN functions
bootscm.import <- function (scm.folder = NULL,
silent=FALSE,
n.bs = NULL,
cov.recoding=NULL,
group.by.cov=NULL,
skip.par.est.import=FALSE,
dofv.forward = 3.84,
dofv.backward = 6.64,
runno = NULL,
return.obj = FALSE
) {
bootscm.obj <- list()
cat.s <- function (txt) { if (silent == FALSE) { cat (txt) } }
if (is.null(scm.folder)) {
scm.folder <- ask.folder()
}
if (is.null(scm.folder)) {
return()
}
if(is.null(group.by.cov)) {
group.by.cov.num <- ask.group.by.cov()
if (group.by.cov.num == "1") { group.by.cov <- FALSE} else { group.by.cov <- TRUE}
}
if (is.null(NULL)) {
cat (paste("Please note that if you are manually recoding the covariates in the \n",
"scm config file, you will have to import the results manually using\n",
"the bootscm.import() function and the 'cov.recoding=...' argument.\n",
"See manual for more details.\n\n", sep=""))
}
cat.s ("Importing bootstrap...\n")
if (is.null(n.bs)) {
scm_dirs <- dir (scm.folder, "scm_dir\\d")
n.bs <- length(scm_dirs)
cat.s (paste("* Found ", n.bs, " scm folders in the bootscm folder.\n", sep=""))
} else {
cat.s (paste("* Trying to read data from ", n.bs, " scm's in the bootscm folder.\n", sep=""))
}
if (n.bs == 0) {
cat.s ("* No scm folders were found in the bootscm folder. Please check correct execution of PsN.\n\n")
return()
}
cat.s ("* Trying to import covariate inclusion data...")
if (file.exists(paste(scm.folder,"/covariate_inclusion.csv", sep=""))) {
cov.incl <- read.csv(paste(scm.folder,"/covariate_inclusion.csv", sep=""))
cat.s ("Converting...")
bootscm.obj <- convert.bootscm.cov.inclusion (cov.incl, group.by.cov = group.by.cov)
bootscm.obj$group.by.cov <- group.by.cov
bootscm.obj$covnams <- colnames(bootscm.obj$results.tab)
if (0 %in% cov.incl$bs_n) {
bootscm.obj$reestimate_final <- TRUE
bootscm.obj$results.tab.orig <- bootscm.obj$results.tab[1,]
bootscm.obj$results.tab <- bootscm.obj$results.tab[-1,]
} else {
bootscm.obj$reestimate_final <- FALSE
}
## Create table of inclusion frequency
incl.freq <- bootscm.obj$results.tab
for (i in 1:length(bootscm.obj$results.tab[,1])) {
incl.freq[i,] <- apply (bootscm.obj$results.tab[1:i,], 2, function (data) { sum (as.num(data)) / length(data) })
}
bootscm.obj$incl.freq <- incl.freq
cat.s ("OK.\n")
} else {
cat.s ("Data not found.\n")
}
cat.s ("* Trying to import individual inclusion data...")
if (file.exists(paste(scm.folder,"/bs_ids.csv", sep=""))) {
bs_ids <- read.csv(paste(scm.folder,"/bs_ids.csv", sep=""))
cat.s ("Converting...")
bootscm.obj$oid <- convert.bootscm.bs.ids (bs_ids)
cat.s ("OK.\n")
} else {
cat.s ("Data not found.\n")
}
if (skip.par.est.import == FALSE) {
cat.s ("* Trying to import covariate parameter estimates...")
if (file.exists(paste(scm.folder, "/scm_dir1/raw_results_bsmod_1.csv", sep=""))) {
cat.s ("Importing...")
tmp <- read.bootscm.par.est(folder=paste(scm.folder,sep=""),
n.bs = n.bs,
cov.recoding=cov.recoding,
dofv.forward=dofv.forward,
dofv.backward=dofv.backward)
bootscm.obj <- c(bootscm.obj, tmp)
bootscm.obj$par.est.first.corr <- tmp$par.est.first * tmp$covariate$sd
cat.s ("OK.\n")
} else {
cat.s ("Data not found.\n")
}
}
cat.s ("* Trying to import final objective function values...")
if (bootscm.obj$reestimate_final) {
if (file.exists(paste(scm.folder,"/ofv_final.csv", sep=""))) {
tmp <- read.csv(paste(scm.folder,"/ofv_final.csv", sep=""))
ofv_final <- tmp
ofv_final$dOFV <- 0
ofv_final[2:length(ofv_final$OFV),]$dOFV <- ofv_final[2:length(ofv_final$OFV),]$OFV - ofv_final[1,]$OFV
# ofv_final <- ofv_final[!(is.na(ofv_final[,2]) | is.na(ofv_final[,4])),]
# ofv_final <- ofv_final[ofv_final$OFV!=0,]
bootscm.obj$dofv <- ofv_final
bootscm.obj$ofv_original <- tmp[1,]$OFV
cat.s ("OK.\n")
} else {
cat.s ("Data not found.\n")
}
} else {
cat.s ("Re-estimation of final models not performed.\n")
}
if(is.null(runno)){
# if (silent==FALSE) {
# cat.s ("\nWhat was the run number of the base model for this bootSCM? ")
# bootscm.obj$runno <- readline()
# }
bootscm.obj$runno <- 1
} else {
bootscm.obj$runno <- runno
}
cat.s ("\n")
c1<-call("assign", pos = 1, "current.bootscm", bootscm.obj, immediate=T)
eval(c1)
if(return.obj) {
return(bootscm.obj)
} else {
return ()
}
}
read.scm.covariate.sd <- function (file, cov.recoding = NULL) {
## calculate standard deviation from PsN's covariate_statistics.txt
## and also return most common covariates and number of levels
tmp <- readLines (file)
cov.lines <- grep ("=> \\{", tmp)
cov.lines <- cov.lines[!(cov.lines %in% grep ("[fractions|factors]", tmp))]
covs <- tmp[cov.lines]
covs <- gsub("[\\'|\\{|=>| ]", "", covs)
factor.lines <- grep ("factors", tmp)
close.lines <- grep ("\\}", tmp)
stats <- list()
stats$covs.sd <- list()
stats$most.common <- list()
stats$n.levels <- list()
for (i in seq(along=covs)) {
tmp.sub <- tmp[((factor.lines[i])+1) : (min(close.lines[close.lines>factor.lines[i]])-1)]
tmp.stats <- get.cov.stats(tmp.sub, covs[i], cov.recoding)
stats$covs.sd[[covs[i]]] <- tmp.stats$sd
stats$most.common[[covs[i]]] <- tmp.stats$most.common
stats$min.val[[covs[i]]] <- tmp.stats$min.val
stats$max.val[[covs[i]]] <- tmp.stats$max.val
stats$n.levels[[covs[i]]] <- tmp.stats$n.levels
}
stats$dichot <- names(stats$n.levels)[stats$n.levels == 2]
return(stats)
}
get.cov.stats <- function (dat, cov.name, cov.recoding) {
dat <- gsub ("[\\'|\\,| ]","", dat)
covs <- strsplit (dat, "=>")
covs.num <- data.frame (t(matrix (nrow=2, as.num(unlist(covs)))))
covs.num$X3 <- 0
if (cov.name %in% names(cov.recoding)) {
recode <- cov.recoding[[cov.name]]
if (length(covs.num[,1]) == length(recode[,1])) {
covs.num[,3] <- recode[match(recode[,1], covs.num[,1]),2]
}
covs.num$X1 <- covs.num$X3
}
covs.list <- rep (covs.num$X1, covs.num$X2)
most.common <- covs.num[covs.num$X2==max(covs.num$X2),]$X1[1]
min.val <- min(covs.num$X1)
max.val <- max(covs.num$X1)
n.levels <- length(unique(covs.num[,1]))
stats <- list ("sd" = sd(covs.list), "most.common" = most.common, "min.val" = min.val, "max.val" = max.val, "n.levels" = n.levels)
return (stats)
}
as.num <- function (dat) {
return (as.numeric (as.character(dat)))
}
convert.most.common <- function (th) {
## For dichotomous covariates, PsN always uses:
## CL = TVCL # for most common value
## CL = TVCL * (1 + THETA(1)) # for other covariate value
## this script recalculates the value if the other implementation is desired
return (-(1-(1/(1+th))))
}
get.pars.from.relations.file <- function (folder) {
par.file <- readLines (paste(folder,"/scm_dir1/relations.txt", sep=""))
grp <- par.file[grep("->\\{", par.file)]
p.grp <- gregexpr ("\\'" , grp)
pars <- c()
for (i in seq(along=p.grp)) {
pars <- c(pars, substr(grp[i], p.grp[[i]][1]+1, p.grp[[i]][2]-1 ))
}
return(unique(pars))
}
reshape.simple <- function (dat) { # simple reshape function
comb <- c()
for (i in seq(along=colnames(dat))) {
comb <- rbind (comb, cbind ("cov" = colnames(dat)[i], "value" = dat[,i]))
}
comb <- data.frame(comb)
comb$value <- as.numeric(as.character(comb$value))
return (comb)
}
read.bootscm.par.est <- function (folder, n.bs = 100, cov.recoding = NULL, verbose = TRUE,
dofv.forward = 3.84, dofv.backward = 6.64){
bs_final <- c()
bs_first <- c()
covariate <- list()
covariate$sd <- c()
covariate$most.common <- c()
covariate$n.levels <- c()
pars <- get.pars.from.relations.file(folder)
first.non.na <- function(dat) {
return(dat[!is.na(dat)][1])
}
add.to.table <- function(tab, row, nams) {
if (is.null(tab)) {
tab <- data.frame(t(c(row)))
colnames(tab) <- nams
}
else {
tab <- rbind(tab, NA)
j <- length(tab[, 1])
for (k in seq(along = nams)) {
if (nams[k] %in% colnames(tab)) {
tab[j, ][[nams[k]]] <- as.numeric(row[k])
}
else {
tab[[nams[k]]] <- NA
tab[j, ][[nams[k]]] <- as.numeric(row)
}
}
}
return(tab)
}
for (j in 1:n.bs) {
if (file.exists(paste(folder, "/scm_dir", j, sep = ""))) {
tmp_full <- read.csv(file = paste(folder, "/scm_dir",
j, "/raw_results_bsmod_", j, ".csv", sep = ""))
cov_cols <- c((grep("ofv", colnames(tmp_full))[1] +
1):(grep("^OM", colnames(tmp_full))[1] -
1))
covs <- tmp_full[, cov_cols]
if (length(grep("th[[:digit:]]", colnames(covs))) >
0) {
covs <- covs[, -(grep("th[[:digit:]]", colnames(covs)))]
}
nams <- cbind(colnames(covs))
# for (i in seq(nams)) {
# splt <- strsplit(nams[i], "\\.")[[1]]
# nams[i] <- paste(splt[1], splt[2], sep = ".")
# }
for (i in seq(pars)) {
sel <- grep(pars[i], substr(nams, 1, nchar(pars[i])))
nams[sel] <- paste(pars[i], substr(nams[sel],
nchar(pars[i]) + 1, nchar(nams[sel])), sep = ".")
}
forward_steps <- unique(tmp_full[tmp_full$action ==
"added", ]$step.num)
tmp_full$row <- 1:length(tmp_full[, 1])
ofv.base <- tmp_full[tmp_full$step.number == 0, ]$ofv
best.model.row <- 0
best.model.ofv <- ofv.base
for (i in forward_steps) {
step.tmp <- tmp_full[tmp_full$step.number ==
i & tmp_full$action == "added", ]
min.tmp <- min(step.tmp$ofv)
if (!is.na(min.tmp)) {
if (min.tmp < (best.model.ofv - dofv.forward)) {
best.tmp <- step.tmp[step.tmp$ofv == min.tmp,
]$row
best.model.row <- best.tmp[1]
best.model.ofv <- min.tmp
}
}
}
backward_steps <- unique(tmp_full[tmp_full$action ==
"removed", ]$step.num)
for (i in backward_steps) {
step.tmp <- tmp_full[tmp_full$step.number ==
i & tmp_full$action == "removed", ]
min.tmp <- min(step.tmp$ofv)
if (!is.na(min.tmp)) {
if (min.tmp < (best.model.ofv + dofv.backward)) {
best.tmp <- step.tmp[step.tmp$ofv == min.tmp,
]$row
best.model.row <- best.tmp[1]
best.model.ofv <- min.tmp
}
}
}
est_final <- tmp_full[best.model.row, cov_cols]
if (length(grep("th[[:digit:]]", colnames(est_final))) >
0) {
est_final <- est_final[, -(grep("th[[:digit:]]",
colnames(est_final)))]
}
est_first <- apply(covs, 2, first.non.na)
names(est_first) <- nams
#if(j==1) browser()
bs_first <- add.to.table(bs_first, est_first, names(est_first))
#bs_first <- rbind(bs_first,est_first)
names(est_final) <- nams
bs_final <- add.to.table(bs_final, as.numeric(est_final),
names(est_final))
stats <- read.scm.covariate.sd(paste(folder, "/scm_dir",
j, "/covariate_statistics.txt", sep = ""), cov.recoding)
std <- stats$covs.sd
std[!is.na(std)] <- as.num(std[!is.na(std)])
if (j == 1) {
nams.sd <- names(std)
covariate$dichot <- stats$dichot
}
covariate$sd <- rbind(covariate$sd, as.num(t(std)))
covariate$most.common <- rbind(covariate$most.common,
unlist(stats$most.common))
covariate$min.val <- rbind(covariate$min.val, unlist(stats$min.val))
covariate$max.val <- rbind(covariate$max.val, unlist(stats$max.val))
covariate$n.levels <- rbind(covariate$n.levels, as.num(t(stats$n.levels)))
}
}
if (verbose == TRUE) {
cat("\n Importing step done. Processing imported data...")
}
colnames(covariate$sd) <- nams.sd
colnames(covariate$n.levels) <- nams.sd
tmp <- covariate$sd
tmp.min <- covariate$min.val
covariate$sd.all <- c()
covs.dichot <- c()
for (i in seq(along = nams)) {
splt <- strsplit(nams[i], "\\.")[[1]]
covariate$sd.all <- cbind(covariate$sd.all, covariate$sd[,
match(splt[2], colnames(tmp))])
covariate$min.val.all <- cbind(covariate$min.val.all,
covariate$min.val[, match(splt[2], colnames(tmp))])
colnames(covariate$sd.all)[i] <- nams[i]
colnames(covariate$min.val.all)[i] <- nams[i]
sel.dichot <- match(splt[2], covariate$dichot)
if (!is.na(sel.dichot)) {
covs.dichot <- c(covs.dichot, nams[i])
}
}
for (i in seq(along = covs.dichot)) {
if (!is.na(match(covs.dichot[i], colnames(bs_first)))) {
min.val <- min(data.frame(covariate$min.val.all)[[covs.dichot[i]]])
sel <- data.frame(covariate$most.common)[[covs.dichot[i]]] !=
min.val
bs_first[[covs.dichot[i]]][sel] <- convert.most.common(bs_first[[covs.dichot[i]]][sel])
bs_final[[covs.dichot[i]]][sel] <- convert.most.common(as.numeric(bs_final[[covs.dichot[i]]][sel]))
}
}
bs_first_norm <- bs_first * covariate$sd.all
bs_final_norm <- bs_final * covariate$sd.all
mean.na <- function(dat) {
# dat <- as.numeric(dat)
# return(mean(dat[!is.na(dat)]))
mean(dat,na.rm = TRUE)
}
sd.na <- function(dat) {
dat <- as.numeric(dat)
return(sd(dat[!is.na(dat)]))
}
rse.na <- function(dat) {
dat <- as.numeric(dat)
return(sd(dat[!is.na(dat)])/mean(dat[!is.na(dat)]))
}
first.step.stats <- rbind(apply(bs_first, 2, mean.na), apply(bs_first,
2, sd.na), apply(bs_first, 2, rse.na))
rownames(first.step.stats) <- c("mean", "sd", "rse")
final.step.stats <- rbind(apply(bs_final, 2, mean.na), apply(bs_final,
2, sd.na), apply(bs_final, 2, rse.na))
rownames(final.step.stats) <- c("mean", "sd", "rse")
create.bias.table <- function(first, final) {
tmp <- reshape.simple(first)
tmp$cov.type <- "Continuous"
if (length(covariate$dichot) > 0) {
tmp[tmp$cov %in% covs.dichot, ]$cov.type <- "Dichotomous"
}
tmp$incl <- c((!is.na(final)) * 1)
tmp <- tmp[order(tmp$incl), ]
tmp[tmp$incl == 0, ]$incl <- "Not included"
tmp[tmp$incl == 1, ]$incl <- "Included"
mn.tmp1 <- aggregate(tmp[tmp$incl == "Included", ]$value,
by = list(tmp[tmp$incl == "Included", ]$cov), mean.na)
never.incl <- unique(tmp$cov)[!(unique(tmp$cov) %in%
mn.tmp1$Group.1)]
if (length(never.incl) > 0) {
# mn.tmp1 <- rbind(mn.tmp1, aggregate(tmp[tmp$cov %in%
# never.incl, ]$value, by = list(tmp[tmp$cov %in%
# never.incl, ]$cov), mean.na))
mn.tmp1.add <- aggregate(tmp[tmp$cov %in% never.incl, ]$value,
by = list(tmp[tmp$cov %in% never.incl, ]$cov),
mean.na)
mn.tmp1.add$x <- NA
mn.tmp1 <- rbind(mn.tmp1, mn.tmp1.add)
}
mn.tmp1 <- mn.tmp1[match(unique(tmp$cov), mn.tmp1$Group.1),]
mn.tmp1.all = aggregate(tmp$value,
by = list(tmp$cov), mean.na)
mn.tmp1.comb <- merge(mn.tmp1 ,mn.tmp1.all,by=c("Group.1"),all.x=T)
names(mn.tmp1.comb) <- c("cov","mean","All")
mn.tmp1.comb$incl <- "Included"
b.stats.incl <- mn.tmp1.comb
# b.stats.incl <- data.frame(cbind(cov = as.character(unique(tmp$cov)),
# mean = mn.tmp1$x, All = as.num(aggregate(tmp$value,
# by = list(tmp$cov), mean.na)$x), incl = "Included"))
mn.tmp2 <- aggregate(tmp[tmp$incl == "Not included",
]$value, by = list(tmp[tmp$incl == "Not included",
]$cov), mean.na)
always.incl <- unique(tmp$cov)[!(unique(tmp$cov) %in%
mn.tmp2$Group.1)]
if (length(always.incl) > 0) {
mn.tmp2.add <- aggregate(tmp[tmp$cov %in% always.incl,
]$value, by = list(tmp[tmp$cov %in% always.incl,
]$cov), mean.na)
mn.tmp2.add$x <- NA
mn.tmp2 <- rbind(mn.tmp2, mn.tmp2.add)
}
mn.tmp2 <- mn.tmp2[match(unique(tmp$cov), mn.tmp2$Group.1),]
mn.tmp2.all = aggregate(tmp$value,
by = list(tmp$cov), mean.na)
mn.tmp2.comb <- merge(mn.tmp2 ,mn.tmp2.all,by=c("Group.1"),all.x=T)
names(mn.tmp2.comb) <- c("cov","mean","All")
mn.tmp2.comb$incl <- "Not Included"
b.stats.nincl <- mn.tmp2.comb
# b.stats.nincl <- data.frame(cbind(cov = as.character(unique(tmp$cov)),
# mean = mn.tmp2$x, All = as.num(aggregate(tmp$value,
# by = list(tmp$cov), mean.na)$x), incl = "Not Included"))
b.stats <- data.frame(rbind(b.stats.incl, b.stats.nincl))
add.nincl <- b.stats.incl[!b.stats.incl$cov %in% b.stats.nincl$cov,
]$cov
add.incl <- b.stats.nincl[!b.stats.nincl$cov %in% b.stats.incl$cov,
]$cov
for (i in seq(along = add.nincl)) {
b.stats <- rbind(b.stats, cbind(cov=as.character(add.nincl[i]), mean=NA,All=NA,
incl="Not Included"))
}
for (i in seq(along = add.incl)) {
b.stats <- rbind(b.stats, cbind(cov=as.character(add.nincl[i]), mean=NA,All=NA,
incl="Included"))
}
bias.dat <- data.frame(b.stats)
bias.dat$bias <- as.num(100 * (as.num(bias.dat$mean) -
as.num(bias.dat$All))/as.num(bias.dat$All))
bias.dat$cov.type <- "Continuous"
if (length(covariate$dichot) > 0) {
bias.dat[bias.dat$cov %in% covs.dichot, ]$cov.type <- "Dichotomous"
}
return(list(table.long = tmp, bias.dat = bias.dat))
}
tab <- create.bias.table(bs_first, bs_final)
tab.norm <- create.bias.table(bs_first_norm, bs_final_norm)
return(list(par.est.first = bs_first, par.est.first.norm = bs_first_norm,
par.est.first.stats = data.frame(first.step.stats), par.est.final = bs_final,
par.est.final.norm = bs_final_norm, par.est.final.stats = data.frame(final.step.stats),
covariate = covariate, bias.dat = tab$bias.dat, bias.dat.norm = tab.norm$bias.dat,
par.est.long = tab$table.long, par.est.long.norm = tab.norm$table.long,
pars = pars))
}
convert.bootscm.cov.inclusion <- function (cov.incl, group.by.cov = FALSE) {
## convert table: discard info about parameter (CL / V / etc.) and relation type (linear / nonlin / etc.) if
n <- max(cov.incl$bs_n)
cov.incl <- cov.incl[,-1]
covs <- colnames(cov.incl)
if (group.by.cov == TRUE) {
covs.names <- c()
for (i in seq(along=covs)) {
tmp_cov <- convert.cov.name (covs[i])
if (!is.na(tmp_cov)) {
covs.names[i] <- tmp_cov
}
}
covs.unq <- unique(covs.names)
results.tab <- data.frame (matrix(0, nrow = length(cov.incl[,1]), ncol=length(covs.unq)))
colnames(results.tab) <- covs.unq
for (i in seq(along=cov.incl[,1])) {
for (j in seq(along=cov.incl[i,])) {
if (cov.incl[i,j] == 1) {
results.tab[i,][[covs.names[j]]] <- 1
}
}
}
} else {
results.tab <- cov.incl[,-(length(cov.incl[1,]))]
covs.names <- colnames(results.tab)
}
## separate off Dummy covariates
res <- list ("n" = n, "results.tab" = results.tab)
if (group.by.cov == FALSE) {
patt <- "\\.X"
} else {
patt <- "^X."
}
cols.dum <- grep(patt, colnames(results.tab))
if (length(cols.dum)>0) {
results.tab.dum <- cbind(results.tab[,cols.dum])
colnames(results.tab.dum) <- gsub(patt, "", colnames(results.tab)[cols.dum])
res$results.tab <- results.tab[,-cols.dum]
res$results.tab.dum <- results.tab.dum[-1,]
}
return (res)
}
convert.cov.name <- function (cov) {
return (strsplit (cov, "\\.")[[1]][2])
}
convert.bootscm.bs.ids <- function (bs_ids) {
ids <- unique (unlist(bs_ids[,-1]))
n <- length(bs_ids[,1])
oid <- data.frame (matrix(0, nrow = n, ncol=length(ids)))
colnames(oid) <- paste("X", ids, sep="")
tmp <- bs_ids[,-1]
for (i in 1:length(tmp[,1])) {
cols <- match(paste("X", tmp[i,], sep=""), colnames(oid))
for (k in seq(along=cols)) {
oid[i,cols[k]] <- oid[i,cols[k]] + 1 # save original ID numbers selected in the bootstrap
}
}
return(oid)
}
ask.folder <- function () {
d <- gsub ("\\./", "", list.dirs (path = ".", pattern="scm", full.names = TRUE))
if (length(d) == 0) { # maybe folder was not named "scm"
d <- gsub ("\\./", "", list.dirs (path = ".", full.names = TRUE))
}
cat ("Import from subfolder (filtered on 'scm'):\n ")
cat (paste (d,"\n"), sep = " ")
cat ("\nFolder with bootSCM data (Enter to abort): ")
ans <- readline()
if (ans == "") {
return()
}
if (!is.na(file.info(ans)$isdir)) {
if (file.info(ans)$isdir) {
return (ans)
} else {
cat("Please choose a valid folder!\n\n")
Recall()
}
} else {
cat("Please choose a valid folder!\n\n")
Recall()
}
}
ask.group.by.cov <- function () {
cat ("\nPlease choose how you want to import covariate inclusion frequencies:\n")
cat (" 1: Not grouped, inclusion frequencies per parameter-covariate relationship\n")
cat (" 2: Grouped, inclusion frequencies per covariate\n")
ans <- readline()
if (ans == "") {
return()
}
if (ans==1|ans==2) {
return (ans)
} else {
cat("Please choose a valid option!\n\n")
Recall()
}
}
list.dirs <- function(path=".", pattern=NULL, all.dirs=FALSE,
full.names=FALSE, ignore.case=FALSE) {
all <- list.files(path, pattern, all.dirs, full.names, recursive=FALSE, ignore.case)
return(all[file.info(paste(path, "/", all, sep=""))$isdir])
}
| /scratch/gouwar.j/cran-all/cranData/xpose4/R/bootscm.R |
#' Read NONMEM output files into Xpose 4
#'
#' These are functions that read in a NONMEM output file (a '*.lst' file) and
#' then format the input.
#'
#'
#' @param filename A NONMEM output file.
#' @param listfile A NONMEM output file.
#' @param object The return value of \code{read.lst(filename)}
#' @return lists of read values.
#' @author Niclas Jonsson, Andrew Hooker & Justin Wilkins
#' @family data functions
#' @name read_NM_output
NULL
#' @describeIn read_NM_output calculates the number and type of parameters included in a
#' NONMEM output file
#' @export
#'
calc.npar <- function(object)
{
##attach(object)
## Thetas
if(!any(is.null(object$thetas)||is.null(object$thetas))) nth <- length(object$thetas)
## SE of the thetas
#if(!any(is.null(object$sethetas)||is.na(object$sethetas))) {
if(!any(is.null(object$sethetas))){
nseth <- length(object$sethetas[!is.na(object$sethetas)])
}
else {
nseth <- 0
}
if(!(is.null(object$omega)||any(is.na(object$omega)))) {
nom <- 0
for(i in 1:length(object$omega)) {
## This only gives back the number of non-zero elements.
## Handling of initial zeros is done in plotsum2
sel <- object$omega[[i]] != 0
if(!any(sel==TRUE)){
nom <- nom + 1
}
##nom <- length(omega[[i]]) + nom
nom <- length(object$omega[[i]][sel]) + nom
}
}
## SE of the omegas
#if(!any(is.null(object$seomegas)||is.na(object$seomegas))) {
if(!any(is.null(object$seomegas))) {
nseom <- 0
for(i in 1:length(object$seomegas)) {
## This only gives back the number of non-zero elements.
## Handling of initial zeros is done in plotsum2
sel <- object$seomegas[[i]] != 0
sel2 <- !is.na(object$seomegas[[i]])
sel3 <- sel & sel2
#if(!any(sel==TRUE)){
# nom <- nom + 1
#}
##nom <- length(omega[[i]]) + nom
nseom <- length(object$seomegas[[i]][sel3]) + nseom
}
}
else {
nseom <- 0
}
## Sigmas
nsi <- 0
if(!(is.null(object$sigma)||any(is.na(object$sigma)))) {
for(i in 1:length(object$sigma)) {
sel <- object$sigma[[i]] != 0
nsi <- length(object$sigma[[i]][sel]) + nsi
}
}
## SE of the sigmas
#if(!any(is.null(object$sesigmas)||is.na(object$sesigmas))) {
if(!any(is.null(object$sesigmas))) {
nsesi <- 0
for(i in 1:length(object$sesigmas)) {
## This only gives back the number of non-zero elements.
## Handling of initial zeros is done in plotsum2
sel <- object$sesigmas[[i]] != 0
sel2 <- !is.na(object$sesigmas[[i]])
sel3 <- sel & sel2
#if(!any(sel==TRUE)){
# nom <- nom + 1
#}
##nom <- length(omega[[i]]) + nom
nsesi <- length(object$sesigmas[[i]][sel3]) + nsesi
}
}
else {
nsesi <- 0
}
npar <- nth + nom + nsi
if(length(nseth) > 0 || length(nseom) > 0 || length(nsesi) > 0) {
ret.list <- list(npar = npar, nth = nth, nseth = nseth, nom =
nom, nseom = nseom, nsi = nsi, nsesi = nsesi)
}
else {
ret.list <- list(npar = npar, nth = nth, nom = nom, nsi = nsi)
}
#invisible(ret.list)
return(ret.list)
}
| /scratch/gouwar.j/cran-all/cranData/xpose4/R/calc.npar.R |
# Xpose 4
# An R-based population pharmacokinetic/
# pharmacodynamic model building aid for NONMEM.
# Copyright (C) 1998-2004 E. Niclas Jonsson and Mats Karlsson.
# Copyright (C) 2005-2008 Andrew C. Hooker, Justin J. Wilkins,
# Mats O. Karlsson and E. Niclas Jonsson.
# Copyright (C) 2009-2010 Andrew C. Hooker, Mats O. Karlsson and
# E. Niclas Jonsson.
# This file is a part of Xpose 4.
# Xpose 4 is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public License
# as published by the Free Software Foundation, either version 3
# of the License, or (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
# You should have received a copy of the GNU Lesser General Public License
# along with this program. A copy can be cound in the R installation
# directory under \share\licenses. If not, see http://www.gnu.org/licenses/.
#' Categorical observations vs. independent variable using stacked bars.
#'
#' Categorical observations vs. independent variable using stacked bars.
#'
#'
#' @param object Xpose data object.
#' @param dv The dependent variable (e.g. \code{"DV"} or \code{"CP"}.)
#' @param idv The independent variable (e.g. \code{"TIME"}.)
#' @param by Conditioning variable
#' @param groups How we should group values in each conditional plot.
#' @param force.by.factor Should we force the data to be treated as factors?
#' @param recur Not used.
#' @param xlb A string giving the label for the x-axis. \code{NULL} if none.
#' @param ylb A string giving the label for the y-axis. \code{NULL} if none.
#' @param subset Subset of data.
#' @param vary.width Should we vary the width of the bars to match amount of
#' information?
#' @param level.to.plot Which levels of the DV to plot.
#' @param refactor.levels Should we refactor the levels?
#' @param main The title of the plot.
#' @param stack Should we stack the bars?
#' @param horizontal Should the bars be horizontal?
#' @param strip Defining how the strips should appear in the conditioning
#' plots.
#' @param scales Scales argument to \code{\link[lattice]{xyplot}}.
#' @param inclZeroWRES Include rows with WRES=0?
#' @param onlyfirst Only include first data point for each individual?
#' @param samp Sample to use in mirror plot (a number).
#' @param aspect Aspect argument to \code{\link[lattice]{xyplot}}.
#' @param auto.key Make a legend.
#' @param mirror Mirror can be \code{FALSE}, \code{TRUE}, 1 or 3.
#' @param mirror.aspect Aspect for mirror.
#' @param pass.plot.list Should the plot list be passed back to user?
#' @param x.cex Size of x axis label.
#' @param y.cex Size of Y axis label.
#' @param main.cex Size of Title.
#' @param mirror.internal Internal stuff.
#' @param \dots Other arguments passed to function.
#' @author Andrew Hooker
#' @keywords methods
#' @examples
#'
#' \dontrun{
#' ## read in table files
#' runno <- 45
#' xpdb <- xpose.data(runno)
#'
#' ## make some stacked bar plots
#' cat.dv.vs.idv.sb(xpdb,idv=NULL,stack=F)
#' cat.dv.vs.idv.sb(xpdb,idv=NULL,stack=F,by="DOSE")
#' cat.dv.vs.idv.sb(xpdb,idv="DOSE")
#' cat.dv.vs.idv.sb(xpdb,idv=NULL,stack=F,by="TIME")
#' cat.dv.vs.idv.sb(xpdb,idv="TIME")
#' cat.dv.vs.idv.sb(xpdb,idv="CAVH")
#' cat.dv.vs.idv.sb(xpdb,idv="TIME",by="DOSE",scales=list(x=list(rot=45)))
#'
#' ## make some mirror plots
#' cat.dv.vs.idv.sb(xpdb,idv="DOSE",mirror=1)
#' cat.dv.vs.idv.sb(xpdb,idv="CAVH",mirror=1,auto.key=F)
#' }
#'
#' @export cat.dv.vs.idv.sb
#' @family specific functions
"cat.dv.vs.idv.sb" <-
function(object,
dv=xvardef("dv",object),
idv=xvardef("idv",object),
by=NULL,
groups=dv,
force.by.factor = FALSE,
recur=F,
xlb=idv,
ylb="Proportion",
subset=NULL,
vary.width=T,
level.to.plot=NULL,
refactor.levels=TRUE,
main=xpose.create.title.text(idv,dv,
"Proportions of",object,subset=subset,...),
stack=TRUE,
horizontal=FALSE,
strip = function(...)
strip.default(...,strip.names=c(TRUE,TRUE)),
scales = list(),
inclZeroWRES = TRUE,
onlyfirst = FALSE,
samp = NULL,
aspect = object@[email protected]$aspect,
auto.key = "Default",#TRUE,
## mirror stuff
mirror = FALSE,
mirror.aspect="fill",
pass.plot.list=FALSE,
x.cex=NULL,
y.cex=NULL,
main.cex=NULL,
mirror.internal=list(strip.missing=missing(strip)),
...){
if(is.null(check.vars(c(dv,idv),
object,silent=FALSE))) {
return()
}
plotTitle <- main
## for MIRROR functionality
arg.list <- formals(cat.dv.vs.idv.sb)
arg.names <- names(arg.list)
new.arg.list <- vector("list",length(arg.names))
names(new.arg.list) <- arg.names
for (argnam in arg.names){
if (argnam=="..."){
next
}
tmp <- get(argnam)
if (is.null(tmp)){
} else {
new.arg.list[[argnam]]=tmp
}
}
if (mirror){
create.mirror(cat.dv.vs.idv.sb,
new.arg.list,mirror,plotTitle,...)
} else { # end if mirror
##Get data
if(!is.null(samp)) {
data <- SData(object,inclZeroWRES,onlyfirst=onlyfirst,
subset=subset,samp=samp)
} else {
data <- Data(object,inclZeroWRES,onlyfirst=onlyfirst,subset=subset)
}
## Strip "missing" data
data <- subset(data, get(dv) != object@Prefs@Miss)
if(any(is.null(data))) return("The subset expression is invalid!\n")
## Make sure by is a factor if requested
if(!is.null(by) && force.by.factor) {
for(b in by) {
data[,b] <- as.factor(data[,b])
}
}
## ## Set up the data
## retlist <- make.sb.data(data,idv,dv,by=by,...)
## ret <- retlist$ret
## dvs <- unique(data[,dv])
## if(vary.width) {
## wdths <- retlist$wdths
## } else {
## wdths <- rep(1,length(retlist$wdths))
## }
## Set up the data
retlist <- make.sb.data(data,idv,dv,by=by,...)
ret <- retlist$ret
if(!is.null(level.to.plot)){
ret <- ret[ret["dv"]==level.to.plot,]
if(refactor.levels){
ret["dv"] <- factor(ret[["dv"]])
}
}
dvs <- unique(ret[,"dv"])
if(is.null(idv)) ret$idv <- "All Values"
## if(vary.width) {
## wdths <- retlist$wdths
## } else {
## wdths <- rep(1,length(retlist$wdths))
## }
## x and y labels
nams <- names(ret)
if(is.null(xlb)){
xlb <- idv
}
if(is.null(ylb)) ylb <- paste("Proportions of ",dv,sep="")
## For sizes of labels
if(!is.null(x.cex)) {
if (is.list(xlb)){
xlb$cex=x.cex
} else {
xlb <- list(xlb,cex=x.cex)
}
}
if(!is.null(y.cex)) {
if (is.list(ylb)){
ylb$cex=y.cex
} else {
ylb <- list(ylb,cex=y.cex)
}
}
if(is.null(main)) {
} else {
if(!is.null(main.cex)) {
if (is.list(main)){
main$cex=main.cex
} else {
main <- list(main,cex=main.cex)
}
}
}
## ##barplot(as.matrix(ret),width=wdths,xlab=xlb,ylab=ylb,legend.text=T)
## ret.stack <- stack(ret)
## ret.stack$level <- row.names(ret)
## ret.stack$ind <- factor(ret.stack$ind,levels=names(ret))
## if(is.null(idv)) ret.stack$ind <- "All Values"
## if(!is.null(level.to.plot)){
## ret.stack <- subset(ret.stack,level==paste(dv,"=",level.to.plot,sep=""))
## }
##if(is.null(idv)) ret.stack$ind <- "All Values"
if(auto.key=="Default"){
auto.key <- list(#title=dv,
#text= paste(dv,"=",dvs, sep = ""),
cex=0.8)
}
## ## Collect the basic plot formula
## bb <- NULL
## if(any(is.null(by))) { ## No conditioning
## formel <- paste("values~ind",sep="")
## } else {
## bys <- paste(by,collapse="*")
## formel <- paste("values~ind","|",bys,sep="")
## }
if(!is.null(by)){
by.loc <- grep("by.var",names(ret))
names(ret)[by.loc] <- by
}
## Collect the basic plot formula
bb <- NULL
if(any(is.null(by))) { ## No conditioning
formel <- paste("proportion~","idv",sep="")
} else {
bys <- paste(by,collapse="*")
#formel <- paste("proportion~","idv","|",bys,sep="")
formel <- paste("proportion~","idv","|",by,sep="")
}
#wdths <- c(12,2,24,90)
#wdths <- wdths/100
#wdths <- c(20,20,2,20)
## values~ind
## xplot <- barchart(formula(formel),data=ret.stack,
## groups=level,stack=T,
## #box.ratio=wdths,
## auto.key=auto.key,#list(columns=length(dvs)),
## xlab=xlb,ylab=ylb,main=main,
## scales=scales,
## aspect=aspect,
## ...)
ret$levs <- ret[["dv"]]
levels(ret$levs) <- paste(groups,"=",levels(ret$levs))
xplot <- barchart(formula(formel),groups=ret$levs,
data=ret,
stack=stack,
horizontal=horizontal,#
#box.ratio=ret$wdth,
auto.key=auto.key,#list(columns=length(dvs)),
xlab=xlb,ylab=ylb,main=main,
scales=scales,
aspect=aspect,
strip=strip,
...)
return(xplot)
}
}
| /scratch/gouwar.j/cran-all/cranData/xpose4/R/cat.dv.vs.idv.sb.R |
#' Categorical (visual) predictive check.
#'
#' Categorical (visual) predictive check plots.
#'
#'
#' @param object Xpose data object.
#' @param dv The dependent variable (e.g. \code{"DV"} or \code{"CP"}.)
#' @param idv The independent variable (e.g. \code{"TIME"}.)
#' @param level.to.plot The levels to plot.
#' @param subset Subset of data.
#' @param histo If \code{FALSE} then a VPC is created, given that \code{idv} is
#' defined.
#' @param median.line Make a median line?
#' @param PI.lines Make prediction interval lines?
#' @param xlb Label for x axis.
#' @param ylb label for y axis.
#' @param main Main title.
#' @param strip Defining how the strips should appear in the conditioning
#' plots.
#' @param \dots Extra arguments passed to the function.
#' @author Andrew C. Hooker
#' @keywords methods
#' @examples
#'
#' \dontrun{
#' ## read in table files
#' runno <- 45
#' xpdb <- xpose.data(runno)
#'
#' ## create proportion (visual) predictive check
#' cat.pc(xpdb,idv=NULL)
#' cat.pc(xpdb,idv="DOSE")
#' cat.pc(xpdb,idv="DOSE",histo=F)
#' cat.pc(xpdb,idv="TIME",histo=T,level.to.plot=1)
#' }
#'
#' @export
#' @family specific functions
cat.pc <-
function(object,
dv=xvardef("dv",object),
idv=xvardef("idv",object),
level.to.plot=NULL,
subset=NULL,
histo=T,
median.line=F,
PI.lines=F,
xlb=if(histo){
paste("Proportion of ",dv)
} else {
paste(idv)
},
ylb=if(histo){
paste("Percent of Total")
} else {
paste("Proportion of Total")
},
main=xpose.create.title.text(NULL,dv,
"Predictive check of",object,subset=subset,...),
strip="Default",
...)
{
##Get data
sdata <- SData(object,inclZeroWRES=TRUE,onlyfirst=FALSE,
subset=subset)
data <- Data(object,inclZeroWRES=TRUE,onlyfirst=FALSE,
subset=subset)
## Strip "missing" data
data <- subset(data, get(dv) != object@Prefs@Miss)
sdata <- subset(sdata, get(dv) != object@Prefs@Miss)
if(any(is.null(data))) return("The subset expression is invalid!\n")
if(any(is.null(sdata))) return("The subset expression is invalid!\n")
## get props for every simulated data set
props <- c()
for(i in 1:max(sdata[,"iter"])){
tmp <- sdata[eval(parse(text=paste("sdata$iter==",i))),]
tmp.retlist <- make.sb.data(tmp,idv,dv,...)
tmp.ret <- tmp.retlist$ret
if(!is.null(level.to.plot)){
tmp.ret <- tmp.ret[tmp.ret["dv"]==level.to.plot,]
}
##tmp.prop <- tmp.ret[paste(sim.dv,"=",level.to.plot,sep=""),]
##tmp.prop$level <- paste(sim.dv,"=",level.to.plot,sep="")
props <- rbind(props,tmp.ret)
}
## get the props for the real data set
retlist <- make.sb.data(data,idv,dv,...)
prop <- retlist$ret
if(!is.null(level.to.plot)){
prop <- prop[prop["dv"]==level.to.plot,]
}
## set up the formula for plotting a histogram of the
## simulated data
var.name <- c()
dv.levels.sim <- unique(props[,"dv"])
dv.levels.real <- unique(prop[,"dv"])
n.dv.levels.sim <- length(dv.levels.sim)
n.dv.levels.real <- length(dv.levels.real)
if(n.dv.levels.real != n.dv.levels.sim){
if(n.dv.levels.sim < n.dv.levels.real){
props[,"dv"] <- factor(props[,"dv"],levels=levels(prop[,"dv"]))
}
if(n.dv.levels.sim > n.dv.levels.real){
prop[,"dv"] <- factor(prop[,"dv"],levels=levels(props[,"dv"]))
}
}
dv.levels <- levels(prop[,"dv"])
n.dv.levels <- length(dv.levels)
if(is.null(idv)) { ## No conditioning
histo=T
if (n.dv.levels==1){
formel <- paste("~proportion",sep="")
} else {
formel <- paste("~proportion|dv",sep="")
var.name <- c(dv)
}
} else {
if (n.dv.levels==1){
formel <- paste("~proportion|idv",sep="")
formel.2 <- paste("real~idv",sep="")
var.name <- c(idv)
} else {
formel <- paste("~proportion|dv+idv",sep="")
formel.2 <- paste("real~idv|by.var",sep="")
var.name <- c(dv,idv)
}
}
if(!histo){
## Set up the data frame for a VPC
num.col.new <- 6
idv.levs <- unique(props[,"idv"])
num.row.new <- n.dv.levels*length(idv.levs)
ret.new <- data.frame(matrix(nrow = num.row.new,
ncol = num.col.new))
names(ret.new) <- c("idv","real","lower","median","upper","by.var")
if(!is.null(levels(props[,"idv"]))){
ret.new["idv"] <- factor(ret.new["idv"],levels=levels(props[,"idv"]))
}
ret.new["by.var"] <- factor(ret.new["by.var"],levels=levels(props[,"dv"]))
i <- 1
for(LEVS in 1:n.dv.levels){
tmp.by=dv.levels[LEVS]
dat1.sim <- props[props[,"dv"] == dv.levels[LEVS], ,drop=F ]
dat1.real <- prop[prop[,"dv"] == dv.levels[LEVS], ,drop=F ]
for(IDV in 1:length(idv.levs)){
tmp.idv=idv.levs[IDV]
dat2.sim <- dat1.sim[dat1.sim[,"idv"] == idv.levs[IDV], ,drop=F ]
dat2.real <- dat1.real[dat1.real[,"idv"] == idv.levs[IDV], ,drop=F ]
tmp.pctls <- quantile(dat2.sim$proportion,probs=c(0.05,0.5,0.95))
tmp.real <- dat2.real$proportion
ret.new[i,"idv"] <- tmp.idv
ret.new[i,"real"] <- tmp.real
ret.new[i,c("lower","median","upper")] <- tmp.pctls
ret.new[i,"by.var"] <- tmp.by
i <- i+1
}
}
}
if(strip=="Default"){
strip <- strip.custom(strip.names=TRUE,
var.name=var.name)
}
if(histo){
xplot <- histogram(formula(formel),data=props,
xlab=xlb,main=main,real.data=prop,
strip=strip,
...,
panel=function(real.data,...){
##tmp.data <- ret.new[ret.new$by.var==dv.levels[panel.number()],]
panel.histogram(...)
panel.abline(v=real.data$proportion[panel.number()],
col="red",lwd=3,...)
}
)
} else {
xplot <-
xyplot(formula(formel.2),
data=ret.new,
type="b",
prepanel = function(x,y,...) {
tmp.data <- ret.new[ret.new$by.var==dv.levels[panel.number()],]
if(is.factor(x)){#length(levs <- unique(x)) < object@[email protected]) {
xlim <- sort(levels(x))
} else {
xlim <- range(x)
}
ylim <- range(c(y,tmp.data$lower,tmp.data$upper))
list(xlim=xlim,ylim=ylim)
},
xlab=xlb,main=main,ylab=ylb,
strip=strip,
...,
panel=function(x,y,subscripts,...){
tmp.data <- ret.new[ret.new$by.var==dv.levels[panel.number()],]
grid.polygon(c(tmp.data$idv,rev(tmp.data$idv)),
c(tmp.data$upper,rev(tmp.data$lower)),
default.units="native",
gp=gpar(fill="green",alpha=0.3,col=NULL,lty=0)
)
panel.xyplot(x,y,...)
if(median.line){
panel.lines(tmp.data$idv,tmp.data$median,type="b",
col="darkgrey",
lty=2)
}
if(PI.lines){
panel.lines(tmp.data$idv,tmp.data$lower,type="b",
col="darkgreen",
lty=2)
panel.lines(tmp.data$idv,tmp.data$upper,type="b",
col="darkgreen",
lty=2)
}
}
)
## grid.polygon(xrecs,y.up.recs,
## default.units="native",
## gp=gpar(fill=PI.ci.up.arcol,alpha=0.3,col=NULL,lty=0)
## )
## ,
## ...)
}
return(xplot)
}
| /scratch/gouwar.j/cran-all/cranData/xpose4/R/cat.pc.R |
#' Generic table functions for Xpose 4
#'
#' These are internal table functions relating to the Xpose summary functions.
#'
#' These are internal Xpose functions for outputting summary tables. They are
#' not intended for direct use.
#'
#' @aliases continuous.table categorical.table
#' @return Internal helper functions for the generic Xpose summary functions.
#' @author Niclas Jonsson, Justin Wilkins and Andrew Hooker
#' @keywords internal
categorical.table <- function(object,
vars,
onlyfirst=TRUE,
subset=xsubset(object),
inclZeroWRES=FALSE,
miss=object@Prefs@Miss) # can be a number
{
data <- Data(object,onlyfirst=onlyfirst,subset=subset,inclZeroWRES=inclZeroWRES)
usemiss <- FALSE
for (nam in vars) {
if(any(is.na(data[[nam]]) | data[[nam]]==miss)) {
usemiss <- TRUE
}
}
if (usemiss == TRUE) {
ret.mat <- matrix(0,ncol=5,nrow=1+length(vars))
ret.mat[1,] <- c("","Category","N","%","Missing")
#ret.mat[1,] <- c("","Category","N","%")
} else {
ret.mat <- matrix(0,ncol=4,nrow=1+length(vars))
ret.mat[1,] <- c("","Category","N","%")
}
i <- 1
for(nam in vars) {
if (is.factor(data[[nam]])) {
i <- i+1
micov <- subset(data[[nam]], is.na(data[[nam]]) | data[[nam]]==miss)
nomicov<- subset(data[[nam]], !is.na(data[[nam]]) & data[[nam]]!=miss)
if (usemiss==TRUE) {
ret.mat[i,] <- c(nam,
paste(levels(data[[nam]]),collapse="\n"),
paste(tabulate(data[[nam]]),collapse="\n"),
paste(sprintf("%.1f",
100*tabulate(data[[nam]])/sum(tabulate(data[[nam]]))),
collapse="\n"),
paste(length(micov)," (",
sprintf("%.1f",
100*length(micov)/(length(micov)+length(nomicov))),
"%)",sep="")
)
} else {
ret.mat[i,] <- c(nam,
paste(levels(data[[nam]]),collapse="\n"),
paste(tabulate(data[[nam]]),collapse="\n"),
paste(sprintf("%.1f",
100*tabulate(data[[nam]])/sum(tabulate(data[[nam]]))),
collapse="\n")
)
}
}
}
class(ret.mat) <- "char.matrix"
return(ret.mat)
}
| /scratch/gouwar.j/cran-all/cranData/xpose4/R/categorical.table.R |
#' Functions changing variable definitions in Xpose 4
#'
#' These functions allow customization of Xpose's graphics settings.
#'
#' Settings can be saved and loaded using \code{\link{export.graph.par}} and
#' \code{\link{import.graph.par}}, respectively.
#'
#' @param object An \code{xpose.data} object.
#' @param classic A logical operator specifying whether the function should
#' assume the classic menu system. This is an internal option and need never be
#' called from the command line.
#' @return An \code{\link{xpose.data}} object (classic == FALSE) or null
#' (classic == TRUE).
#' @author Niclas Jonsson & Justin Wilkins
#' @seealso \code{\link{xpose.plot.default}},\code{\link{xpose.panel.default}},
#' \code{\link{xpose.plot.bw}},\code{\link{xpose.panel.bw}},
#' \code{\link{xpose.plot.default}},\code{\link{import.graph.par}},
#' \code{\link{export.graph.par}},\code{\link{plot.default}},
#' \code{\link{par}},\code{\link{import.graph.par}},\code{\link[lattice]{panel.abline}},
#' \code{\link[lattice]{panel.lmline}},\code{\link{lm}},\code{\link[lattice]{panel.loess}},
#' \code{\link{loess.smooth}},\code{\link{loess}},\code{\link[lattice]{panel.bwplot}},
#' \code{\link[lattice]{shingle}},\code{reorder.factor}
#' @examples
#'
#' \dontrun{
#' ## xpdb5 is an Xpose data object
#' ## We expect to find the required NONMEM run and table files for run
#' ## 5 in the current working directory
#' xpdb5 <- xpose.data(5)
#'
#' ## Change default miscellaneous graphic preferences
#' xpdb5 <- change.misc.graph.par(xpdb5)
#'
#' ## Change default linear regression line preferences, creating a new
#' ## object
#' xpdb5.a <- change.lm.graph.par(xpdb5)
#'
#' ## Change conditioning preferences
#' xpdb5 <- change.cond.graph.par(xpdb5)
#' }
#'
#'
#' @name change_graphical_parameters
#' @family data functions
NULL
#' @describeIn change_graphical_parameters change settings for the line of
#' identity.
#' @export
change.ab.graph.par <- function(object, classic = FALSE)
{
data <- object
cat("These are the current settings for lines of identity:\n\n")
cat(paste("Use line of identity:",data@[email protected]$abline,sep=" "),"\n")
cat(paste("Line color:",data@[email protected]$ablcol,sep=" "),"\n")
cat(paste("Line type:", data@[email protected]$abllty,sep=" "),"\n")
cat(paste("Line width:",data@[email protected]$abllwd,sep=" "),"\n")
cat("\n")
# gr.stngs <- xp.gr.stngs
cat("Should a line of identity be included by default?\n\n")
cat("(A 2-element list specifying whether, and if so, what\n")
cat("type of line to automatically overlay on plots. NULL indicates\n")
cat("no line unless overridden by a specific function (e.g. dv.vs.pred),\n")
cat("c(1,1) indicates an x:y line, and c(1,2) indicates an x:2y line,\n")
cat("for example. See R help on 'panel.abline' for more information.): \n\n")
ans <- readline()
if(ans!="") {
data@[email protected]$abline <- ans
}
cat("\nSpecify a new line color or leave blank to keep unchanged.\n\n")
cat("(Specified as an integer or a text string. A full list is obtained \n")
cat("by the R command 'colours()'. The default is black (col=1).): \n\n")
ans <- readline()
if ((ans!="") && (!is.na(as.numeric(ans)))) {
data@[email protected]$ablcol <- as.numeric(ans)
} else {
data@[email protected]$ablcol <- ans
}
cat("\nSpecify a new line type or leave blank to keep unchanged.\n\n")
cat("(Line types are specified as an integer (0=blank, 1=solid, \n")
cat("2=dashed, 3=dotted, 4=dotdash, 5=longdash, 6=twodash).) \n\n")
ans <- readline()
if(ans!="") {
data@[email protected]$abllty <- as.numeric(ans)
}
cat("\nSpecify a new line width or leave blank to keep unchanged.\n\n")
cat("(A positive real number): \n\n")
ans <- readline()
if(ans!="") {
data@[email protected]$abllwd <- as.numeric(ans)
}
if (classic==TRUE) {
c1<-call("assign",paste("xpdb", object@Runno, sep = ""), data, immediate=T, envir = .GlobalEnv)
eval(c1)
c2<-call("assign",pos = 1, ".cur.db", eval(as.name(paste("xpdb", object@Runno, sep = ""))))
eval(c2)
return(cat(""))
} else {
return(data)
}
}
| /scratch/gouwar.j/cran-all/cranData/xpose4/R/change.ab.graph.par.R |
#' @describeIn change_graphical_parameters sets preferences for box-and-whisker plots
#' @export
change.bw.graph.par <- function(object, classic = FALSE)
{
data <- object
cat("These are the current settings for the box-and-whisker plots:\n\n")
cat(paste("Horizontal:",data@[email protected]$bwhoriz,sep=" "),"\n")
cat(paste("Height-to-interbox space ratio:",data@[email protected]$bwratio,sep=" "),"\n")
cat(paste("Proportional widths:", data@[email protected]$bwvarwid,sep=" "),"\n")
cat(paste("Dot plotting character:",data@[email protected]$bwdotpch,sep=" "),"\n")
cat(paste("Dot colour:",data@[email protected]$bwdotcol,sep=" "),"\n")
cat(paste("Dot scale:",data@[email protected]$bwdotcex,sep=" "),"\n")
cat(paste("Rectangle fill colour:",data@[email protected]$bwrecfill,sep=" "),"\n")
cat(paste("Rectangle line colour:",data@[email protected]$bwreccol,sep=" "),"\n")
cat(paste("Rectangle line type:",data@[email protected]$bwreclty,sep=" "),"\n")
cat(paste("Rectangle line width:", data@[email protected]$bwreclwd,sep=" "),"\n")
cat(paste("Umbrella line colour:",data@[email protected]$bwumbcol,sep=" "),"\n")
cat(paste("Umbrella line type:",data@[email protected]$bwumblty,sep=" "),"\n")
cat(paste("Umbrella line width:",data@[email protected]$bwumblwd,sep=" "),"\n")
cat(paste("Outlier plotting character:",data@[email protected]$bwoutpch,sep=" "),"\n")
cat(paste("Outlier colour:", data@[email protected]$bwoutcol,sep=" "),"\n")
cat(paste("Outlier scale:",data@[email protected]$bwoutcex,sep=" "),"\n")
cat("\n")
# gr.stngs <- xp.gr.stngs
cat("Should the plots be horizontal?\n\n")
cat("(TRUE or FALSE.): \n\n")
ans <- readline()
if(ans!="") {
data@[email protected]$bwhoriz <- as.logical(ans)
}
cat("\nSpecify a new box height to interbox space ratio, or leave blank\n")
cat("to keep unchanged.\n\n")
cat("(Specified as number. The default is 1.5.): \n\n")
ans <- readline()
if(ans!="") {
data@[email protected]$bwratio <- as.numeric(ans)
}
cat("Should the box widths be proportional?\n\n")
cat("(If TRUE, widths of boxplots are proportional to the number of points\n")
cat("used in creating them. The default is FALSE.): \n\n")
ans <- readline()
if(ans!="") {
data@[email protected]$bwvarwid <- as.logical(ans)
}
cat("\nSpecify a new plotting character for dots or leave blank to keep.\n\n")
cat("unchanged.\n\n")
cat("(Specified as an integer. See R help on \'points\'. The default is\n")
cat("16.): \n\n")
ans <- readline()
if(ans!="") {
data@[email protected]$bwdotpch <- as.numeric(ans)
}
cat("\nSpecify a new dot color or leave blank to keep unchanged.\n\n")
cat("(Specified as an integer or a text string. A full list is obtained \n")
cat("by the R command 'colours()'. The default is black (col=1).): \n\n")
ans <- readline()
if ((ans!="") && (!is.na(as.numeric(ans)))) {
data@[email protected]$bwdotcol <- as.numeric(ans)
} else {
data@[email protected]$bwdotcol <- ans
}
cat("\nSpecify a new dot scale or leave blank to keep unchanged.\n\n")
cat("(The amount by which plotting text and symbols should be scaled\n")
cat("relative to the default. 'NULL' and 'NA' are equivalent to '1.0'.): \n\n")
ans <- readline()
if(ans!="") {
data@[email protected]$bwdotcex <- as.numeric(ans)
}
cat("\nSpecify a new rectangle fill color or leave blank to keep unchanged.\n\n")
cat("(Specified as an integer or a text string. A full list is obtained \n")
cat("by the R command 'colours()'. The default is transparent.): \n\n")
ans <- readline()
if ((ans!="") && (!is.na(as.numeric(ans)))) {
data@[email protected]$bwrecfill <- as.numeric(ans)
} else {
data@[email protected]$bwrecfill <- ans
}
cat("\nSpecify a new rectangle line color or leave blank to keep unchanged.\n\n")
cat("(Specified as an integer or a text string. A full list is obtained \n")
cat("by the R command 'colours()'. The default is blue (col=2).): \n\n")
ans <- readline()
if ((ans!="") && (!is.na(as.numeric(ans)))) {
data@[email protected]$bwreccol <- as.numeric(ans)
} else {
data@[email protected]$bwreccol <- ans
}
cat("\nSpecify a new rectangle line type or leave blank to keep unchanged.\n\n")
cat("(Line types are specified as an integer (0=blank, 1=solid, \n")
cat("2=dashed, 3=dotted, 4=dotdash, 5=longdash, 6=twodash).) \n\n")
ans <- readline()
if(ans!="") {
data@[email protected]$bwreclty <- as.numeric(ans)
}
cat("\nSpecify a new rectangle line width or leave blank to keep unchanged.\n\n")
cat("(A positive real number): \n\n")
ans <- readline()
if(ans!="") {
data@[email protected]$bwreclwd <- as.numeric(ans)
}
cat("\nSpecify a new umbrella line color or leave blank to keep unchanged.\n\n")
cat("(Specified as an integer or a text string. A full list is obtained \n")
cat("by the R command 'colours()'. The default is blue (col=2).): \n\n")
ans <- readline()
if ((ans!="") && (!is.na(as.numeric(ans)))) {
data@[email protected]$bwumbcol <- as.numeric(ans)
} else {
data@[email protected]$bwumbcol <- ans
}
cat("\nSpecify a new umbrella line type or leave blank to keep unchanged.\n\n")
cat("(Line types are specified as an integer (0=blank, 1=solid, \n")
cat("2=dashed, 3=dotted, 4=dotdash, 5=longdash, 6=twodash).) \n\n")
ans <- readline()
if(ans!="") {
data@[email protected]$bwumblty <- as.numeric(ans)
}
cat("\nSpecify a new umbrella line width or leave blank to keep unchanged.\n\n")
cat("(A positive real number): \n\n")
ans <- readline()
if(ans!="") {
data@[email protected]$bwumblwd <- as.numeric(ans)
}
cat("\nSpecify a new plotting character for outliers or leave blank to keep.\n\n")
cat("unchanged.\n\n")
cat("(Specified as an integer. See R help on \'points\'. The default is\n")
cat("1.): \n\n")
ans <- readline()
if(ans!="") {
data@[email protected]$bwdotpch <- as.numeric(ans)
}
cat("\nSpecify a new outlier color or leave blank to keep unchanged.\n\n")
cat("(Specified as an integer or a text string. A full list is obtained \n")
cat("by the R command 'colours()'. The default is blue.): \n\n")
ans <- readline()
if ((ans!="") && (!is.na(as.numeric(ans)))) {
data@[email protected]$bwdotcol <- as.numeric(ans)
} else {
data@[email protected]$bwdotcol <- ans
}
cat("\nSpecify a new outlier scale or leave blank to keep unchanged.\n\n")
cat("(The amount by which plotting text and symbols should be scaled\n")
cat("relative to the default. 'NULL' and 'NA' are equivalent to '1.0'.): \n\n")
ans <- readline()
if(ans!="") {
data@[email protected]$bwdotcex <- as.numeric(ans)
}
if (classic==TRUE) {
c1<-call("assign",paste("xpdb", object@Runno, sep = ""), data, immediate=T, envir = .GlobalEnv)
eval(c1)
c2<-call("assign",pos = 1, ".cur.db", eval(as.name(paste("xpdb", object@Runno, sep = ""))))
eval(c2)
return(cat(""))
} else {
return(data)
}
}
| /scratch/gouwar.j/cran-all/cranData/xpose4/R/change.bw.graph.par.R |
#' Functions changing miscellaneous parameter settings in Xpose 4
#'
#' These functions allow viewing and changing of settings relating to subsets,
#' categorical threshold values, documentation and numbers indicating missing
#' data values.
#'
#' @param object An \code{xpose.data} object.
#' @param classic A logical operator specifying whether the function should
#' assume the classic menu system. This is an internal option and need never be
#' called from the command line.
#' @param dv.cat.limit The limit for which we treat DV as categorical. If
#' there are \code{dv.cat.limit} or less unique dv values then dv is treated as
#' categorical.
#' @param cat.limit The limit for which we treat a list of values as
#' categorical. If there are \code{cat.limit} or less unique values then the
#' list is treated as categorical.
#' @param listall A logical operator specifying whether the items in the
#' database should be listed.
#' @param to.cat.vec A vector of strings specifying the names of the
#' categorical variables that should be transformed to continuous.
#' @param to.cont.vec A vector of strings specifying the names of the
#' continuous variables that should be transformed to categorical.
#' @param change.type.vec A vector of strings specifying the names of the
#' variables that should be transformed to/from continuous/categorical.
#' @param \dots arguments passed to other functions.
#' @param value This is the value that will be replaced in the xpose data
#' object \code{object}. \code{value} is used in the \dQuote{replacement
#' function} version of these functions. That is the form where we have
#' \code{function.name(object) <- value}. If \code{value} is \code{NULL} then
#' the functions prompt the user for a value. For \code{change.cat.levels},
#' \code{value} is the categorical limit \code{cat.limit}. For
#' \code{change.dv.cat.levels}, \code{value} is the DV categorical limit
#' \code{dv.cat.limit}. For \code{change.cat.cont}, \code{value} is the
#' \code{change.type.vec}. See the examples below.
#' @return An \code{\link{xpose.data}} object, except \code{get.doc}, which
#' returns the value of object@Doc.
#' @author Andrew Hooker, Niclas Jonsson & Justin Wilkins
#' @seealso \code{\link{Data}}, \code{\link{SData}}, \code{\link{subset}},
#' \code{\link{xpose.data}}
#' @keywords methods
#' @examples
#'
#' \dontrun{
#' ## xpdb5 is an Xpose data object
#' ## We expect to find the required NONMEM run and table files for run
#' ## 5 in the current working directory
#' xpdb5 <- xpose.data(5)
#'
#' ## Change default subset
#' xpdb5 <- change.subset(xpdb5)
#'
#' ## Set documentation field
#' xpdb5 <- set.doc(xpdb5)
#' ## View it
#' view.doc(xpdb5)
#'
#' ## change the categorical limit for the dv variable
#' change.dv.cat.levels(xpdb5) <- 10
#'
#' ## change the categorical limit for non DV variables
#' change.cat.levels(xpdb5) <- 2
#' ## or
#' xpdb5 <- change.cat.levels(xpdb5,cat.levels=2)
#'
#' ## chnage variables from categorical to continuous
#' xpdb5 <- change.cat.cont(xpdb5,to.cat.vec=c("AGE"),to.cont.vec=c("SEX"))
#' xpdb5 <- change.cat.cont(xpdb5,change.type.vec=c("AGE","SEX"))
#' change.cat.cont(xpdb5) <- c("AGE","SEX")
#' }
#'
#' @name change_misc_parameters
#' @family data functions
NULL
#' @describeIn change_misc_parameters allows interchange between categorical and continuous
#' data formats within the Xpose database. This in turn affects how plots are
#' drawn.
#' @export
change.cat.cont <-
function(object,
listall=TRUE,
classic=FALSE,
to.cat.vec=NULL,
to.cont.vec=NULL,
change.type.vec=NULL,
...){
if(!is.null(change.type.vec)){
for(j in change.type.vec){
if(is.na(pmatch(j, names(object@Data)))) {
cat("Couldn't find",j,"in the current database. Skipping!\n")
next
}
if(is.factor(object@Data[,j])) {
to.cont.vec <- c(to.cont.vec,j)
} else {
to.cat.vec <- c(to.cat.vec,j)
}
}
}
if(is.null(to.cont.vec) & is.null(to.cat.vec) & is.null(change.type.vec)){
if(listall) {
db.names(object)
}
}
if(is.null(to.cont.vec) & is.null(to.cat.vec) & is.null(change.type.vec)){
cat("\nPlease type the names of any CATEGORICAL variables you\n")
cat("want to change into continuous, one per line, and end with a\n")
cat("blank line:\n")
cats <- scan(what=character())
} else {
cats <- to.cont.vec
}
if(length(cats)){
for(i in cats) {
if(is.na(pmatch(i, names(object@Data)))) {
cat("Couldn't find",i,"in the current database. Skipping!\n")
next
}
if(is.factor(object@Data[,i])){
cat("\n Transforming",i,"from categorical to continuous\n",sep=" ")
object@Data[,i] <- as.numeric(levels(object@Data[,i]))[object@Data[,i]]
} else {
cat(" ",i," is already continuous, no changes made", sep="")
}
}
}
if(is.null(to.cont.vec) & is.null(to.cat.vec) & is.null(change.type.vec)){
cat("Please type the names of any CONTINUOUS variables you\n")
cat("want to change into categorical, one per line, and end with a\n")
cat("blank line:\n")
conts <- scan(what=character())
} else {
conts <- to.cat.vec
}
if(length(conts)){
for(i in conts) {
if(is.na(pmatch(i, names(object@Data)))) {
cat("Couldn't find",i,"in current database. Skipping!\n")
next
}
if(!is.factor(object@Data[,i])){
cat("\n Transforming",i,"from continuous to categorical\n",sep=" ")
object@Data[,i] <- as.factor(object@Data[,i])
} else {
cat(" ",i," is already categorical, no changes made\n", sep="")
}
}
}
if (classic==TRUE) {
c1<-call("assign",paste("xpdb", object@Runno, sep = ""), data, immediate=T, envir = .GlobalEnv)
eval(c1)
c2<-call("assign",pos = 1, ".cur.db", eval(as.name(paste("xpdb", object@Runno, sep = ""))))
eval(c2)
}
return(object)
}
#' @describeIn change_misc_parameters allows interchange between categorical and continuous
#' data formats within the Xpose database. This in turn affects how plots are
#' drawn.
#' @export
"change.cat.cont<-" <-
function(object,
listall=TRUE,
classic=FALSE,
to.cat.vec=NULL,
to.cont.vec=NULL,
...,
value){
object <- change.cat.cont(object,listall=listall,calssic=classic,
to.cat.vec=to.cat.vec,
to.cont.vec=to.cont.vec,
change.type.vec=value,
...)
return(object)
}
| /scratch/gouwar.j/cran-all/cranData/xpose4/R/change.cat.cont.R |
#' @describeIn change_misc_parameters change settings for the number of unique data
#' values required in a variable in order to define it as continuous for ordinary
#' variables.
#' @export
change.cat.levels <- function(object,
classic = FALSE,
cat.limit=NULL,
...){
if(is.null(cat.limit)){
cat("\nPlease type the number of unique data values beneath which a\n")
cat("variable will be treated as categorical (it is currently\n")
cat("set to ",object@[email protected],".) (0=exit):\n",sep="")
ans <- readline()
} else {
ans <- cat.limit
}
ans <- as.numeric(ans)
if (is.na(ans)){
cat(paste("The data value must be numeric\n",
"Nothing has been changed\n"))
return(object)
}
if(ans == 0) {
cat(paste("Nothing has been changed\n"))
return(object)
}
if (ans<0){
cat(paste("The data value must be greater than zero\n",
"Nothing has been changed\n"))
return(object)
}
if (!is.na(ans)) {
object@[email protected] <- ans
Data(object) <- object@Data
if (classic==TRUE) {
c1<-call("assign",paste("xpdb", object@Runno, sep = ""), data, immediate=T, envir = .GlobalEnv)
eval(c1)
c2<-call("assign",pos = 1, ".cur.db", eval(as.name(paste("xpdb", object@Runno, sep = ""))))
eval(c2)
}
}
return(object)
}
#' @describeIn change_misc_parameters change settings for the number of unique data
#' values required in a variable in order to define it as continuous for ordinary
#' variables.
#' @export
"change.cat.levels<-" <-
function(object,
classic=FALSE,
...,
value){
object <- change.cat.levels(object,calssic=classic,cat.limit=value,...)
return(object)
}
| /scratch/gouwar.j/cran-all/cranData/xpose4/R/change.cat.levels.R |
#' @describeIn change_graphical_parameters sets preferences for conditioning
#' @export
change.cond.graph.par <- function(object, classic = FALSE)
{
data <- object
cat("These are the current conditioning settings:\n\n")
cat(paste("Condition on:",data@[email protected]$condvar,sep=" "),"\n")
cat(paste("Order by:",data@[email protected]$ordby,sep=" "),"\n")
cat(paste("Ordering function:",data@[email protected]$byordfun,sep=" "),"\n")
cat(paste("Default number of shingles:", data@[email protected]$shingnum,sep=" "),"\n")
cat(paste("Shingle overlap:", data@[email protected]$shingol,sep=" "),"\n")
cat("\n")
# gr.stngs <- xp.gr.stngs
cat("Use a variable to condition plots made by Xpose?\n\n")
cat("(A string of the variable name to condition on, can also\n")
cat("be NULL, press ENTER/RETURN to leave it as it is): \n\n")
ans <- readline()
if(ans == "NULL") {
ans <- NULL
data@[email protected]$condvar <- ans
} else {
if(ans!="") {
data@[email protected]$condvar <- ans
}
}
cat("Use a variable to reorder factorial variables during conditioning?\n\n")
cat("(A string with the name of a variable to be used to reorder\n")
cat("any factorial conditioning variables. The variable is used in a\n")
cat("call to the R 'reorder.factor' function.): \n\n")
ans <- readline()
if(ans!="") {
data@[email protected]$ordby <- ans
}
cat("Specify a function for use with conditioning using categorical\n")
cat("variables.\n\n")
cat("(The name of the function to be used when reordering a\n")
cat("factor conditioning variable. Can be 'mean', 'median', etc.): \n\n")
ans <- readline()
if(ans!="") {
data@[email protected]$byordfun <- ans
}
cat("Specify the number of shingles to be used when conditioning on a\n")
cat("continuous variable.\n\n")
cat("(The number of shingles ('parts') a continuous\n")
cat("conditioning variable should be divided into.): \n\n")
ans <- readline()
if(ans!="") {
data@[email protected]$shingnum <- as.numeric(ans)
}
cat("Specify the amount of overlap between adjacent shingles: \n\n")
ans <- readline()
if(ans!="") {
data@[email protected]$shingol <- as.numeric(ans)
}
if (classic==TRUE) {
c1<-call("assign",paste("xpdb", object@Runno, sep = ""), data, immediate=T, envir = .GlobalEnv)
eval(c1)
c2<-call("assign",pos = 1, ".cur.db", eval(as.name(paste("xpdb", object@Runno, sep = ""))))
eval(c2)
return(cat(""))
} else {
return(data)
}
}
| /scratch/gouwar.j/cran-all/cranData/xpose4/R/change.cond.graph.par.R |
#' @describeIn change_graphical_parameters responsible for dilution
#' preferences
#' @export
"change.dil.graph.par" <- function(object, classic = FALSE)
{
data <- object
cat("These are the current data dilution settings:\n\n")
cat(paste("Dilution type:",data@[email protected]$diltype,sep=" "),"\n")
cat(paste("Fraction to be diluted:",data@[email protected]$dilfrac,sep=" "),"\n")
cat(paste("Dilution confidence interval:", data@[email protected]$dilci,sep=" "),"\n")
cat("\n")
# gr.stngs <- xp.gr.stngs
cat("Stratified dilution?\n\n")
cat("(NULL specifies random dilution without stratification, and is the\n")
cat("default. Anything else indicates that stratified dilution is to be used.): \n\n")
ans <- readline()
if(ans!="") {
data@[email protected]$diltype <- ans
}
cat("Specify the fraction eligible for dilution.\n\n")
cat("(a number, between 0 and 1, defining the fraction of the data to\n")
cat("be diluted. The default is 0.7.): \n\n")
ans <- readline()
if(ans!="") {
data@[email protected]$dilfrac <- as.numeric(ans)
}
cat("Specify the confidence interval for stratified dilution.\n\n")
cat("(a number, between 0 and 1, defining the range of the data\n")
cat("eligible for dilution. The default is 0.95.): \n\n")
ans <- readline()
if(ans!="") {
data@[email protected]$dilci <- as.numeric(ans)
}
if (classic==TRUE) {
c1<-call("assign",paste("xpdb", object@Runno, sep = ""), data, immediate=T, envir = .GlobalEnv)
eval(c1)
c2<-call("assign",pos = 1, ".cur.db", eval(as.name(paste("xpdb", object@Runno, sep = ""))))
eval(c2)
return(cat(""))
} else {
return(data)
}
}
| /scratch/gouwar.j/cran-all/cranData/xpose4/R/change.dil.graph.par.R |
change.dispersion <-
function(first=TRUE)
{
value <- .cur.db@[email protected]$disp
if (first==TRUE){
cat("Use a dispersion factor (null/true)\n")
if (is.null(value)) {
cat("The current value is NULL...\n")
} else {
cat("The current value is",value,"...\n")
}
cat("\nPlease type the new value ")
}
ans <- readline()
if(ans == "NULL" || ans == "null") {
.cur.db@[email protected]$disp <- NULL
c1<-call("assign",pos = 1, ".cur.db", .cur.db)
eval(c1)
invisible()
return()
} else {
if(ans == "true" || ans == "TRUE") {
.cur.db@[email protected]$disp <- TRUE
c1<-call("assign",pos = 1, ".cur.db", .cur.db)
eval(c1)
invisible()
return()
} else {
cat("Please enter NULL or TRUE ")
Recall(first=FALSE)
}
}
}
| /scratch/gouwar.j/cran-all/cranData/xpose4/R/change.dispersion.R |
#' @describeIn change_misc_parameters change settings for the number of unique data
#' values required in a variable in order to define it as continuous for the dependent variable.
#' @export
change.dv.cat.levels <- function(object,
classic = FALSE,
dv.cat.limit=NULL,
...){
if(is.null(dv.cat.limit)){
cat("\nPlease type the number of unique data values beneath which the\n")
cat("dependent variable will be treated as categorical (it is currently\n")
cat("set to ",object@[email protected],".) (0=exit):\n",sep="")
ans <- readline()
} else {
ans <- dv.cat.limit
}
ans <- as.numeric(ans)
if (is.na(ans)){
cat(paste("The data value must be numeric\n",
"Nothing has been changed\n"))
return(object)
}
if(ans == 0) {
cat(paste("Nothing has been changed\n"))
return(object)
}
if (ans<0){
cat(paste("The data value must be greater than zero\n",
"Nothing has been changed\n"))
return(object)
}
if (!is.na(ans)) {
object@[email protected] <- ans
Data(object) <- object@Data
if (classic==TRUE) {
c1<-call("assign",paste("xpdb", object@Runno, sep = ""), data, immediate=T, envir = .GlobalEnv)
eval(c1)
c2<-call("assign",pos = 1, ".cur.db", eval(as.name(paste("xpdb", object@Runno, sep = ""))))
eval(c2)
}
}
return(object)
}
#' @describeIn change_misc_parameters change settings for the number of unique data
#' values required in a variable in order to define it as continuous for the dependent variable.
#' @export
"change.dv.cat.levels<-" <-
function(object,
classic=FALSE,
...,
value){
object <- change.dv.cat.levels(object,calssic=classic,dv.cat.limit=value,...)
return(object)
}
| /scratch/gouwar.j/cran-all/cranData/xpose4/R/change.dv.cat.levels.R |
# Xpose 4
# An R-based population pharmacokinetic/
# pharmacodynamic model building aid for NONMEM.
# Copyright (C) 1998-2004 E. Niclas Jonsson and Mats Karlsson.
# Copyright (C) 2005-2008 Andrew C. Hooker, Justin J. Wilkins,
# Mats O. Karlsson and E. Niclas Jonsson.
# Copyright (C) 2009-2010 Andrew C. Hooker, Mats O. Karlsson and
# E. Niclas Jonsson.
# This file is a part of Xpose 4.
# Xpose 4 is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public License
# as published by the Free Software Foundation, either version 3
# of the License, or (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
# You should have received a copy of the GNU Lesser General Public License
# along with this program. A copy can be cound in the R installation
# directory under \share\licenses. If not, see http://www.gnu.org/licenses/.
"change.graphical.par" <-
function() {
choices <- c("Return to the previous menu ->",
"Change general plot settings",
"Change settings for the smooth",
"Change settings for the linear regression line",
"Change settings for the line of identity",
"Change settings for labelling points",
"Change settings for box-and-whisker plots",
"Change dilution settings",
"Change prediction interval (PI) settings",
"Change conditioning settings",
"Reset graphical parameters to factory settings",
"Export graphical settings to a file",
"Import graphical settings from a file"
)
title="\nGRAPHICAL PARAMETERS MENU\n \\main\\preferences\\Change graphical parameters"
pick <- menu(choices,title=title)
qx <- 0
switch(pick+1,
qx <- 2,
qx <- 1,
change.misc.graph.par(get(".cur.db"), classic = T),
change.smooth.graph.par(get(".cur.db"), classic = T),
change.lm.graph.par(get(".cur.db"), classic = T),
change.ab.graph.par(get(".cur.db"), classic = T),
change.label.par(get(".cur.db"), classic = T),
change.bw.graph.par(get(".cur.db"), classic = T),
change.dil.graph.par(get(".cur.db"), classic = T),
change.pi.graph.par(get(".cur.db"), classic = T),
change.cond.graph.par(get(".cur.db"), classic = T),
reset.graph.par(get(".cur.db"), classic = T),
export.graph.par(get(".cur.db")),
import.graph.par(get(".cur.db"), classic = T),
)
if(qx == 2) {
return(invisible(2))
} else {
if(qx == 1) {
return(invisible(0))
} else {
Recall()
}
}
}
| /scratch/gouwar.j/cran-all/cranData/xpose4/R/change.graphical.par.R |
#' @describeIn change_graphical_parameters responsible for labelling preferences
#' @export
"change.label.par" <- function(object, classic = FALSE)
{
data <- object
cat("These are the current labelling settings:\n\n")
cat(paste("Label points:",data@[email protected]$ids,sep=" "),"\n")
cat(paste("Labelling style:", data@[email protected]$idsmode,sep=" "),"\n")
cat(paste("Extremes:",data@[email protected]$idsext,sep=" "),"\n")
cat(paste("Label size:",data@[email protected]$idscex,sep=" "),"\n")
cat(paste("Direction:", data@[email protected]$idsdir,sep=" "),"\n")
cat("\n")
# gr.stngs <- xp.gr.stngs
cat("Label the data points with ID values?\n\n")
cat("(TRUE or NULL): \n\n")
ans <- readline()
if(ans!="") {
data@[email protected]$ids <- ans
}
cat("Label all points, or extremes only?\n\n")
cat("(NULL specifies extremes, and is the default. Anything else \n")
cat("indicates that all points should be labelled.): \n\n")
ans <- readline()
if(ans!="") {
data@[email protected]$idsmode <- ans
}
cat("Specify the extremes to use for labelling points.\n\n")
cat("(A number between 0 and 1. The default is 0.05 (only the most \n")
cat("extreme 5% of points are labelled).): \n\n")
ans <- readline()
if(ans!="") {
data@[email protected]$idsext <- as.numeric(ans)
}
cat("Specify a new point scale or leave blank to keep unchanged.\n\n")
cat("(The amount by which plotting text and symbols should be scaled\n")
cat("relative to the default. 'NULL' and 'NA' are equivalent to '1.0'.): \n\n")
ans <- readline()
if(ans!="") {
data@[email protected]$idscex <- as.numeric(ans)
}
cat("Specify the direction for labelling or leave blank to keep unchanged.\n\n")
cat("(Possible values are 'up', 'down' and 'both'.): \n\n")
ans <- readline()
if(ans!="") {
data@[email protected]$idsdir <- ans
}
if (classic==TRUE) {
c1<-call("assign",paste("xpdb", object@Runno, sep = ""), data, immediate=T, envir = .GlobalEnv)
eval(c1)
c2<-call("assign",pos = 1, ".cur.db", eval(as.name(paste("xpdb", object@Runno, sep = ""))))
eval(c2)
return(cat(""))
} else {
return(data)
}
}
| /scratch/gouwar.j/cran-all/cranData/xpose4/R/change.label.par.R |
#' @describeIn change_graphical_parameters responsible for linear regression
#' lines.
#' @export
"change.lm.graph.par" <- function(object, classic = FALSE)
{
data <- object
cat("These are the current settings for linear regression lines:\n\n")
cat(paste("Use linear regression line:",data@[email protected]$lmline,sep=" "),"\n")
cat(paste("Line color:",data@[email protected]$lmcol,sep=" "),"\n")
cat(paste("Line type:", data@[email protected]$lmlty,sep=" "),"\n")
cat(paste("Line width:",data@[email protected]$lmlwd,sep=" "),"\n")
cat("\n")
# gr.stngs <- xp.gr.stngs
cat("Should linear regression lines be included by default?\n\n")
cat("(TRUE or FALSE(=NULL).): \n\n")
ans <- readline()
if(ans!="") {
if (ans=="NULL") {
ans = "FALSE"
}
data@[email protected]$suline <- as.logical(ans)
}
cat("\nSpecify a new line color or leave blank to keep unchanged.\n\n")
cat("(Specified as an integer or a text string. A full list is obtained \n")
cat("by the R command 'colours()'. The default is blue.): \n\n")
ans <- readline()
if ((ans!="") && (!is.na(as.numeric(ans)))) {
data@[email protected]$lmcol <- as.numeric(ans)
} else {
data@[email protected]$lmcol <- ans
}
cat("\nSpecify a new line type or leave blank to keep unchanged.\n\n")
cat("(Line types are specified as an integer (0=blank, 1=solid, \n")
cat("2=dashed, 3=dotted, 4=dotdash, 5=longdash, 6=twodash).) \n\n")
ans <- readline()
if(ans!="") {
data@[email protected]$lmlty <- as.numeric(ans)
}
cat("\nSpecify a new line width or leave blank to keep unchanged.\n\n")
cat("(A positive real number): \n\n")
ans <- readline()
if(ans!="") {
data@[email protected]$lmlwd <- as.numeric(ans)
}
if (classic==TRUE) {
c1<-call("assign",paste("xpdb", object@Runno, sep = ""), data, immediate=T, envir = .GlobalEnv)
eval(c1)
c2<-call("assign",pos = 1, ".cur.db", eval(as.name(paste("xpdb", object@Runno, sep = ""))))
eval(c2)
return(cat(""))
} else {
return(data)
}
}
| /scratch/gouwar.j/cran-all/cranData/xpose4/R/change.lm.graph.par.R |
# Xpose 4
# An R-based population pharmacokinetic/
# pharmacodynamic model building aid for NONMEM.
# Copyright (C) 1998-2004 E. Niclas Jonsson and Mats Karlsson.
# Copyright (C) 2005-2008 Andrew C. Hooker, Justin J. Wilkins,
# Mats O. Karlsson and E. Niclas Jonsson.
# Copyright (C) 2009-2010 Andrew C. Hooker, Mats O. Karlsson and
# E. Niclas Jonsson.
# This file is a part of Xpose 4.
# Xpose 4 is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public License
# as published by the Free Software Foundation, either version 3
# of the License, or (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
# You should have received a copy of the GNU Lesser General Public License
# along with this program. A copy can be cound in the R installation
# directory under \share\licenses. If not, see http://www.gnu.org/licenses/.
"change.medianNorm"<-
function(first=TRUE)
{
value <- .cur.db@[email protected]$medianNorm
if (first==TRUE){
cat("Normalize to median (true/false)\n")
if (is.null(value)) {
cat("The current value is NULL...\n")
} else {
cat("The current value is",value,"...\n")
}
cat("\nPlease type the new value ")
}
ans <- readline()
if(ans == "FALSE" || ans == "FALSE") {
.cur.db@[email protected]$medianNorm <- FALSE
c1<-call("assign",pos = 1, ".cur.db", .cur.db)
eval(c1)
invisible()
return()
} else {
if(ans == "true" || ans == "TRUE") {
.cur.db@[email protected]$medianNorm <- TRUE
c1<-call("assign",pos = 1, ".cur.db", .cur.db)
eval(c1)
invisible()
return()
} else {
cat("Please enter TRUE or FALSE ")
Recall(first=FALSE)
}
}
}
| /scratch/gouwar.j/cran-all/cranData/xpose4/R/change.medianNorm.R |
#' @describeIn change_graphical_parameters sets basic graphics parameters,
#' including plot type, point type and size, colour, line type, and line width.
#' @export
change.misc.graph.par <- function(object, classic = FALSE)
{
data <- object
cat("These are the current general plot settings:\n\n")
cat(paste("Type:",data@[email protected]$type,sep=" "),"\n")
cat(paste("Plotting character:", data@[email protected]$pch,sep=" "),"\n")
cat(paste("Point size:",data@[email protected]$cex,sep=" "),"\n")
cat(paste("Color:",data@[email protected]$col,sep=" "),"\n")
cat(paste("Line type:", data@[email protected]$lty,sep=" "),"\n")
cat(paste("Line width:",data@[email protected]$lwd,sep=" "),"\n")
cat(paste("Grid:",data@[email protected]$grid,sep=" "),"\n")
cat(paste("Aspect:",data@[email protected]$aspect,sep=" "),"\n")
cat("\n")
# gr.stngs <- xp.gr.stngs
cat("Specify a new plot type or leave blank to keep unchanged.\n\n")
cat("(1-character string giving the type of plot desired. The\n")
cat("following values are possible, for details, see \'plot\': \'\"p\"\'\n")
cat("for points, \'\"l\"\' for lines, \'\"b\"\' for both.): \n\n")
ans <- readline()
if(ans!="") {
data@[email protected]$type <- ans
}
cat("\nSpecify a new plotting character or leave blank to keep unchanged.\n\n")
cat("(Specified as an integer. See R help on \'points\'. The default is\n")
cat("1, an open circle.): \n\n")
ans <- readline()
if(ans!="") {
data@[email protected]$pch <- as.numeric(ans)
}
cat("\nSpecify a new point scale or leave blank to keep unchanged.\n\n")
cat("(The amount by which plotting text and symbols should be scaled\n")
cat("relative to the default. 'NULL' and 'NA' are equivalent to '1.0'.): \n\n")
ans <- readline()
if(ans!="") {
data@[email protected]$cex <- as.numeric(ans)
}
cat("\nSpecify a new line color or leave blank to keep unchanged.\n\n")
cat("(Specified as an integer or a text string. A full list is obtained \n")
cat("by the R command 'colours()'. The default is blue (col=4).): \n\n")
ans <- readline()
if ((ans!="") && (!is.na(as.numeric(ans)))) {
data@[email protected]$col <- as.numeric(ans)
} else {
data@[email protected]$col <- ans
}
cat("\nSpecify a new line type or leave blank to keep unchanged.\n\n")
cat("(Line types are specified as an integer (0=blank, 1=solid, \n")
cat("2=dashed, 3=dotted, 4=dotdash, 5=longdash, 6=twodash).) \n\n")
ans <- readline()
if(ans!="") {
data@[email protected]$lty <- as.numeric(ans)
}
cat("\nSpecify a new line width or leave blank to keep unchanged.\n\n")
cat("(A positive real number): \n\n")
ans <- readline()
if(ans!="") {
data@[email protected]$lwd <- as.numeric(ans)
}
if (classic==TRUE) {
c1<-call("assign",paste("xpdb", object@Runno, sep = ""), data, immediate=T, envir = .GlobalEnv)
eval(c1)
c2<-call("assign",pos = 1, ".cur.db", eval(as.name(paste("xpdb", object@Runno, sep = ""))))
eval(c2)
return(cat(""))
} else {
return(data)
}
}
| /scratch/gouwar.j/cran-all/cranData/xpose4/R/change.misc.graph.par.R |
#' @describeIn change_misc_parameters change the value to use as
#' 'missing'.
#' @export
"change.miss" <- function(object, classic=FALSE)
{
data <- object
cat("\nPlease type the number to be treated as missing data (it is currently\n")
cat("set to",data@Prefs@Miss,") (0=exit)\n")
ans <- readline()
if(ans == "0")
return(cat(""))
if (is.na(as.numeric(ans))) {
ans <- NULL
return(cat("The data value must be numeric.\n"))
# Recall(object)
}
if (!is.na(as.numeric(ans))) {
data@Prefs@Miss <- as.numeric(ans)
if (classic==TRUE) {
c1<-call("assign",paste("xpdb", object@Runno, sep = ""), data, immediate=T, envir = .GlobalEnv)
eval(c1)
c2<-call("assign",pos = 1, ".cur.db", eval(as.name(paste("xpdb", object@Runno, sep = ""))))
eval(c2)
return(cat(""))
} else {
return(data)
}
}
}
| /scratch/gouwar.j/cran-all/cranData/xpose4/R/change.miss.R |
# Xpose 4
# An R-based population pharmacokinetic/
# pharmacodynamic model building aid for NONMEM.
# Copyright (C) 1998-2004 E. Niclas Jonsson and Mats Karlsson.
# Copyright (C) 2005-2008 Andrew C. Hooker, Justin J. Wilkins,
# Mats O. Karlsson and E. Niclas Jonsson.
# Copyright (C) 2009-2010 Andrew C. Hooker, Mats O. Karlsson and
# E. Niclas Jonsson.
# This file is a part of Xpose 4.
# Xpose 4 is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public License
# as published by the Free Software Foundation, either version 3
# of the License, or (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
# You should have received a copy of the GNU Lesser General Public License
# along with this program. A copy can be cound in the R installation
# directory under \share\licenses. If not, see http://www.gnu.org/licenses/.
"change.onlyfirst"<-
function(first=TRUE)
{
value <- .cur.db@[email protected]$onlyfirst
if (first==TRUE){
cat("Use all lines in a data file (true/false)\n")
if (is.null(value)) {
cat("The current value is NULL...\n")
} else {
cat("The current value is",value,"...\n")
}
cat("\nPlease type the new value ")
}
ans <- readline()
if(ans == "FALSE" || ans == "FALSE") {
.cur.db@[email protected]$onlyfirst <- FALSE
c1<-call("assign",pos = 1, ".cur.db", .cur.db)
eval(c1)
invisible()
return()
} else {
if(ans == "true" || ans == "TRUE") {
.cur.db@[email protected]$onlyfirst <- TRUE
c1<-call("assign",pos = 1, ".cur.db", .cur.db)
eval(c1)
invisible()
return()
} else {
cat("Please enter TRUE or FALSE ")
Recall(first=FALSE)
}
}
}
| /scratch/gouwar.j/cran-all/cranData/xpose4/R/change.onlyfirst.R |
# Xpose 4
# An R-based population pharmacokinetic/
# pharmacodynamic model building aid for NONMEM.
# Copyright (C) 1998-2004 E. Niclas Jonsson and Mats Karlsson.
# Copyright (C) 2005-2008 Andrew C. Hooker, Justin J. Wilkins,
# Mats O. Karlsson and E. Niclas Jonsson.
# Copyright (C) 2009-2010 Andrew C. Hooker, Mats O. Karlsson and
# E. Niclas Jonsson.
# This file is a part of Xpose 4.
# Xpose 4 is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public License
# as published by the Free Software Foundation, either version 3
# of the License, or (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
# You should have received a copy of the GNU Lesser General Public License
# along with this program. A copy can be cound in the R installation
# directory under \share\licenses. If not, see http://www.gnu.org/licenses/.
#' Change parameter scope.
#'
#' Function to change the parameter scope.
#'
#'
#' @param object The xpose data object.
#' @param listall whether we should list all the current parameters.
#' @param classic true if used in the classic menu system (for internal use).
#' @return If classic then return nothing. Otherwise return the new data
#' object.
#' @author Andrew C. Hooker
#' @keywords methods
#' @export change.parm
"change.parm"<-
function(object, listall=TRUE, classic=FALSE)
{
data <- object
if(listall) {
db.names(object)
}
cat("Please type the names of the parameters you want to use\n")
cat("and finish with a blank line. Note that no data checking\n")
cat("is done during this step - so type carefully.\n")
covs <- scan(what = character())
data@Prefs@Xvardef$parms <- covs
if (classic==TRUE) {
c1<-call("assign",paste("xpdb", object@Runno, sep = ""), data, immediate=T, envir = .GlobalEnv)
eval(c1)
c2<-call("assign",pos = 1, ".cur.db", eval(as.name(paste("xpdb", object@Runno, sep = ""))))
eval(c2)
return(cat(""))
} else {
return(data)
}
}
| /scratch/gouwar.j/cran-all/cranData/xpose4/R/change.parm.R |
#' @describeIn change_graphical_parameters responsible for prediction interval plotting preferences
#' @export
"change.pi.graph.par" <- function(object, classic = FALSE)
{
data <- object
cat("These are the current settings for prediction intervals:\n\n")
cat(paste("PI limits:",data@[email protected]$PIlimits,sep=" "),"\n")
cat(paste("Upper limit plot type:",data@[email protected]$PIuptyp,sep=" "),"\n")
cat(paste("Lower limit plot type:",data@[email protected]$PIdotyp,sep=" "),"\n")
cat(paste("Median plot type:",data@[email protected]$PImetyp,sep=" "),"\n")
cat(paste("Upper limit line colour:",data@[email protected]$PIupcol,sep=" "),"\n")
cat(paste("Lower limit line colour:",data@[email protected]$PIdocol,sep=" "),"\n")
cat(paste("Median line colour:",data@[email protected]$PImecol,sep=" "),"\n")
cat(paste("Upper limit line type:",data@[email protected]$PIuplty,sep=" "),"\n")
cat(paste("Lower limit line type:",data@[email protected]$PIdolty,sep=" "),"\n")
cat(paste("Median line type:",data@[email protected]$PImelty,sep=" "),"\n")
cat(paste("Upper limit line width:",data@[email protected]$PIuplwd,sep=" "),"\n")
cat(paste("Lower limit line width:",data@[email protected]$PIdolwd,sep=" "),"\n")
cat(paste("Median line width:",data@[email protected]$PImelwd,sep=" "),"\n")
cat("\n")
# gr.stngs <- xp.gr.stngs
cat("Specify the upper limit of the prediction interval.\n\n")
cat("(a number, between 0 and 1. The default is 0.975.): \n\n")
ans <- readline()
if(ans!="") {
PIuplimit <- as.numeric(ans)
}
cat("\nSpecify the lower limit of the prediction interval.\n\n")
cat("(a number, between 0 and 1. The default is 0.025.): \n\n")
ans <- readline()
if(ans!="") {
PIdolimit <- as.numeric(ans)
}
data@[email protected]$PIlimits = c(PIdolimit, PIuplimit)
cat("\nSpecify a new plot type for the upper PI limit, or leave blank to keep\n")
cat("unchanged.\n\n")
cat("(1-character string giving the type of plot desired. The\n")
cat("following values are possible, for details, see \'plot\': \'\"p\"\'\n")
cat("for points, \'\"l\"\' for lines, or \'\"b\"\' for both.): \n\n")
ans <- readline()
if(ans!="") {
data@[email protected]$PIuptyp <- ans
}
cat("\nSpecify a new plot type for the lower PI limit, or leave blank to keep\n")
cat("unchanged.\n\n")
cat("(1-character string giving the type of plot desired. The\n")
cat("following values are possible, for details, see \'plot\': \'\"p\"\'\n")
cat("for points, \'\"l\"\' for lines, or \'\"b\"\' for both.): \n\n")
ans <- readline()
if(ans!="") {
data@[email protected]$PIdotyp <- ans
}
cat("\nSpecify a new plot type for the median, or leave blank to keep\n")
cat("unchanged.\n\n")
cat("(1-character string giving the type of plot desired. The\n")
cat("following values are possible, for details, see \'plot\': \'\"p\"\'\n")
cat("for points, \'\"l\"\' for lines, or \'\"b\"\' for both.): \n\n")
ans <- readline()
if(ans!="") {
data@[email protected]$PImetyp <- ans
}
cat("\nSpecify a new upper limit line color or leave blank to keep unchanged.\n\n")
cat("(Specified as an integer or a text string. A full list is obtained \n")
cat("by the R command 'colours()'. The default is black.): \n\n")
ans <- readline()
if ((ans!="") && (!is.na(as.numeric(ans)))) {
data@[email protected]$PIupcol <- as.numeric(ans)
} else {
data@[email protected]$PIupcol <- ans
}
cat("\nSpecify a new lower limit line color or leave blank to keep unchanged.\n\n")
cat("(Specified as an integer or a text string. A full list is obtained \n")
cat("by the R command 'colours()'. The default is black.): \n\n")
ans <- readline()
if ((ans!="") && (!is.na(as.numeric(ans)))) {
data@[email protected]$PIdocol <- as.numeric(ans)
} else {
data@[email protected]$PIdocol <- ans
}
cat("\nSpecify a new median line color or leave blank to keep unchanged.\n\n")
cat("(Specified as an integer or a text string. A full list is obtained \n")
cat("by the R command 'colours()'. The default is black.): \n\n")
ans <- readline()
if ((ans!="") && (!is.na(as.numeric(ans)))) {
data@[email protected]$PImecol <- as.numeric(ans)
} else {
data@[email protected]$PImecol <- ans
}
cat("\nSpecify a new upper limit line type or leave blank to keep unchanged.\n\n")
cat("(Line types are specified as an integer (0=blank, 1=solid, \n")
cat("2=dashed, 3=dotted, 4=dotdash, 5=longdash, 6=twodash).) \n\n")
ans <- readline()
if(ans!="") {
data@[email protected]$PIuplty <- as.numeric(ans)
}
cat("\nSpecify a new lower limit line type or leave blank to keep unchanged.\n\n")
cat("(Line types are specified as an integer (0=blank, 1=solid, \n")
cat("2=dashed, 3=dotted, 4=dotdash, 5=longdash, 6=twodash).) \n\n")
ans <- readline()
if(ans!="") {
data@[email protected]$PIdolty <- as.numeric(ans)
}
cat("\nSpecify a new median line type or leave blank to keep unchanged.\n\n")
cat("(Line types are specified as an integer (0=blank, 1=solid, \n")
cat("2=dashed, 3=dotted, 4=dotdash, 5=longdash, 6=twodash).) \n\n")
ans <- readline()
if(ans!="") {
data@[email protected]$PImelty <- as.numeric(ans)
}
cat("\nSpecify a new upper limit line width or leave blank to keep unchanged.\n\n")
cat("(A positive real number): \n\n")
ans <- readline()
if(ans!="") {
data@[email protected]$PIuplwd <- as.numeric(ans)
}
cat("\nSpecify a new lower limit line width or leave blank to keep unchanged.\n\n")
cat("(A positive real number): \n\n")
ans <- readline()
if(ans!="") {
data@[email protected]$PIdolwd <- as.numeric(ans)
}
cat("\nSpecify a new median line width or leave blank to keep unchanged.\n\n")
cat("(A positive real number): \n\n")
ans <- readline()
if(ans!="") {
data@[email protected]$PImelwd <- as.numeric(ans)
}
if (classic==TRUE) {
c1<-call("assign",paste("xpdb", object@Runno, sep = ""), data, immediate=T, envir = .GlobalEnv)
eval(c1)
c2<-call("assign",pos = 1, ".cur.db", eval(as.name(paste("xpdb", object@Runno, sep = ""))))
eval(c2)
return(cat(""))
} else {
return(data)
}
}
| /scratch/gouwar.j/cran-all/cranData/xpose4/R/change.pi.graph.par.R |
#' @describeIn change_graphical_parameters sets preferences for loess smooths.
#' @export
"change.smooth.graph.par" <- function(object, classic = FALSE)
{
data <- object
cat("These are the current settings for the smooth:\n\n")
cat(paste("Use smooth:",data@[email protected]$suline,sep=" "),"\n")
cat(paste("Line color:",data@[email protected]$sucol,sep=" "),"\n")
cat(paste("Line type:", data@[email protected]$sulty,sep=" "),"\n")
cat(paste("Line width:",data@[email protected]$sulwd,sep=" "),"\n")
cat(paste("Span:",data@[email protected]$suspan,sep=" "),"\n")
cat(paste("Degree:",data@[email protected]$sudegr,sep=" "),"\n")
cat("\n")
# gr.stngs <- xp.gr.stngs
cat("Should smooths be included by default?\n\n")
cat("(If not NULL, the value of the string specifies the y variable to\n")
cat("use.): \n\n")
ans <- readline()
if(ans!="") {
data@[email protected]$suline <- ans
}
cat("\nSpecify a new line color or leave blank to keep unchanged.\n\n")
cat("(Specified as an integer or a text string. A full list is obtained \n")
cat("by the R command 'colours()'. The default is blue (col=4).): \n\n")
ans <- readline()
if ((ans!="") && (!is.na(as.numeric(ans)))) {
data@[email protected]$sucol <- as.numeric(ans)
} else {
data@[email protected]$sucol <- ans
}
cat("\nSpecify a new line type or leave blank to keep unchanged.\n\n")
cat("(Line types are specified as an integer (0=blank, 1=solid, \n")
cat("2=dashed, 3=dotted, 4=dotdash, 5=longdash, 6=twodash).) \n\n")
ans <- readline()
if(ans!="") {
data@[email protected]$sulty <- as.numeric(ans)
}
cat("\nSpecify a new line width or leave blank to keep unchanged.\n\n")
cat("(A positive real number): \n\n")
ans <- readline()
if(ans!="") {
data@[email protected]$sulwd <- as.numeric(ans)
}
cat("\nSpecify a new smoothness parameter or leave blank to keep unchanged.\n\n")
cat("(A positive real number between 0 and 1): \n\n")
ans <- readline()
if(ans!="") {
data@[email protected]$suspan <- as.numeric(ans)
}
cat("\nSpecify a new polynomial degree or leave blank to keep unchanged.\n\n")
cat("(A positive real number between 0 and 2): \n\n")
ans <- readline()
if(ans!="") {
data@[email protected]$sudegr <- as.numeric(ans)
}
if (classic==TRUE) {
c1<-call("assign",paste("xpdb", object@Runno, sep = ""), data, immediate=T, envir = .GlobalEnv)
eval(c1)
c2<-call("assign",pos = 1, ".cur.db", eval(as.name(paste("xpdb", object@Runno, sep = ""))))
eval(c2)
return(cat(""))
} else {
return(data)
}
}
| /scratch/gouwar.j/cran-all/cranData/xpose4/R/change.smooth.graph.par.R |
# Xpose 4
# An R-based population pharmacokinetic/
# pharmacodynamic model building aid for NONMEM.
# Copyright (C) 1998-2004 E. Niclas Jonsson and Mats Karlsson.
# Copyright (C) 2005-2008 Andrew C. Hooker, Justin J. Wilkins,
# Mats O. Karlsson and E. Niclas Jonsson.
# Copyright (C) 2009-2010 Andrew C. Hooker, Mats O. Karlsson and
# E. Niclas Jonsson.
# This file is a part of Xpose 4.
# Xpose 4 is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public License
# as published by the Free Software Foundation, either version 3
# of the License, or (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
# You should have received a copy of the GNU Lesser General Public License
# along with this program. A copy can be cound in the R installation
# directory under \share\licenses. If not, see http://www.gnu.org/licenses/.
"change.steppit"<-
function(first=TRUE)
{
value <- .cur.db@[email protected]$steppit
if (first==TRUE){
cat("Use a stepwise search (true/false)\n")
if (is.null(value)) {
cat("The current value is NULL...\n")
} else {
cat("The current value is",value,"...\n")
}
cat("\nPlease type the new value ")
}
ans <- readline()
if(ans == "FALSE" || ans == "FALSE") {
.cur.db@[email protected]$steppit <- FALSE
c1<-call("assign",pos = 1, ".cur.db", .cur.db)
eval(c1)
invisible()
return()
} else {
if(ans == "true" || ans == "TRUE") {
.cur.db@[email protected]$steppit <- TRUE
c1<-call("assign",pos = 1, ".cur.db", .cur.db)
eval(c1)
invisible()
return()
} else {
cat("Please enter TRUE or FALSE ")
Recall(first=FALSE)
}
}
}
| /scratch/gouwar.j/cran-all/cranData/xpose4/R/change.steppit.R |
#' @describeIn change_misc_parameters is used for setting the data item's subset field. To
#' specify a subset of the data to process, you use the variable names and the
#' regular R selection operators. To combine a subset over two or more
#' variables, the selection expressions for the two variables are combined
#' using R's unary logical operators.
#'
#' The variable names are those that are specified in the NONMEM table files
#' (e.g. PRED, TIME, SEX).
#'
#' The selection operators are: == (equal) != (not equal) || (or) > (greater
#' than) < (less than)
#'
#' For example, to specify that TIME less than 24 should be processed, you type
#' the expression: TIME < 24.
#'
#' The unary logical operators are: & (and) | (or)
#'
#' For example, to specify TIME less than 24 and males (SEX equal to 1), you
#' type the expression: TIME < 24 & SEX == 1
#'
#' This subset selection scheme works on all variables, including ID numbers.
#'
#' The subset selection is not entirely stable. For example, there is no check
#' that the user enters a valid expression, nor that the user specifies
#' existing variable names. An erroneous expression will not become evident
#' until a plot is attempted and the expression takes effect.
#'
#' @export
"change.subset" <- function(object, classic = FALSE)
{
data <- object
print.flag.help <- function() {
cat("
Subset selection help
---------------------
To specify a subset of the data to process, you use the variable names
and the regular R \"selection\" operators. To combine a subset over two
or more variables, the selection expressions for the two variables are
combined using R\'s unary logical operators.
The variable names are those that are specified in the NONMEM table
files (e.g. PRED, TIME, SEX).
The \"selection\" operators are:
== (equal)
!= (not equal)
|| (or)
> (greater than)
< (less than)
For example, to specify that TIME less than 24 should be processed, you
type the expression: TIME < 24.
The unary logical operators are:
& (and)
| (or)
For example, to specify TIME less than 24 and males (SEX equal to 1), you
type:TIME < 24 & SEX == 1
This subset selection scheme works on all variables, including ID numbers.
The subset selection is not entirely stable. For example, there is no
check that the user enters a valid expression, nor that the user specifies
existing variable names. An erroneous expression will not become evident
until a plot is attempted and the expression takes effect.
")
}
cat("The current subset expression is:\n")
cat(object@Prefs@Subset,"\n\n")
cat("Type the expression that will evaluate to the logical vector which\n")
cat("indicates the subset you want to use. Type h to get help, q to \n")
cat("leave it as it is or NULL to unspecify:\n")
ans <- readline()
if(ans == "q")
return(cat(""))
if(ans == "n" || ans == "NULL") {
ans <- NULL
data@Prefs@Subset <- ans
if (classic==TRUE) {
c1<-call("assign",paste("xpdb", object@Runno, sep = ""), data, immediate=T, envir = .GlobalEnv)
eval(c1)
c2<-call("assign",pos = 1, ".cur.db", eval(as.name(paste("xpdb", object@Runno, sep = ""))))
eval(c2)
return(cat(""))
} else {
return(data)
}
} else if(ans == "h") {
print.flag.help()
} else {
data@Prefs@Subset <- ans
if (classic==TRUE) {
c1<-call("assign",paste("xpdb", object@Runno, sep = ""), data, immediate=T, envir = .GlobalEnv)
eval(c1)
c2<-call("assign",pos = 1, ".cur.db", eval(as.name(paste("xpdb", object@Runno, sep = ""))))
eval(c2)
return(cat(""))
} else {
return(data)
}
}
}
| /scratch/gouwar.j/cran-all/cranData/xpose4/R/change.subset.R |
# Xpose 4
# An R-based population pharmacokinetic/
# pharmacodynamic model building aid for NONMEM.
# Copyright (C) 1998-2004 E. Niclas Jonsson and Mats Karlsson.
# Copyright (C) 2005-2008 Andrew C. Hooker, Justin J. Wilkins,
# Mats O. Karlsson and E. Niclas Jonsson.
# Copyright (C) 2009-2010 Andrew C. Hooker, Mats O. Karlsson and
# E. Niclas Jonsson.
# This file is a part of Xpose 4.
# Xpose 4 is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public License
# as published by the Free Software Foundation, either version 3
# of the License, or (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
# You should have received a copy of the GNU Lesser General Public License
# along with this program. A copy can be cound in the R installation
# directory under \share\licenses. If not, see http://www.gnu.org/licenses/.
"change.use.ids"<-
function(first=TRUE)
{
value <- .cur.db@[email protected]$plot.ids
if (first==TRUE){
cat("Use ID labels in GAM plots (true/false)\n")
if (is.null(value)) {
cat("The current value is NULL...\n")
} else {
cat("The current value is",value,"...\n")
}
cat("\nPlease type the new value ")
}
ans <- readline()
if(ans == "FALSE" || ans == "FALSE") {
.cur.db@[email protected]$plot.ids <- FALSE
c1<-call("assign",pos = 1, ".cur.db", .cur.db)
eval(c1)
invisible()
return()
} else {
if(ans == "true" || ans == "TRUE") {
.cur.db@[email protected]$plot.ids <- TRUE
c1<-call("assign",pos = 1, ".cur.db", .cur.db)
eval(c1)
invisible()
return()
} else {
cat("Please enter TRUE or FALSE ")
Recall(first=FALSE)
}
}
}
| /scratch/gouwar.j/cran-all/cranData/xpose4/R/change.use.ids.R |
# Xpose 4
# An R-based population pharmacokinetic/
# pharmacodynamic model building aid for NONMEM.
# Copyright (C) 1998-2004 E. Niclas Jonsson and Mats Karlsson.
# Copyright (C) 2005-2008 Andrew C. Hooker, Justin J. Wilkins,
# Mats O. Karlsson and E. Niclas Jonsson.
# Copyright (C) 2009-2010 Andrew C. Hooker, Mats O. Karlsson and
# E. Niclas Jonsson.
# This file is a part of Xpose 4.
# Xpose 4 is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public License
# as published by the Free Software Foundation, either version 3
# of the License, or (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
# You should have received a copy of the GNU Lesser General Public License
# along with this program. A copy can be cound in the R installation
# directory under \share\licenses. If not, see http://www.gnu.org/licenses/.
#' Changes the name of an Xpose data item
#'
#' This function allows the names of data items in the Xpose database to be
#' changed.
#'
#' This function facilitates the changing of data item names in the object@Data
#' slot.
#'
#' @param object An \code{xpose.data} object.
#' @param classic A logical operator specifying whether the function should
#' assume the classic menu system. This is an internal option and need never be
#' called from the command line.
#' @return An \code{\link{xpose.data}} object.
#' @author Niclas Jonsson & Justin Wilkins
#' @seealso \code{\link{Data}},\code{\link{SData}},\code{\link{xpose.data}}
#' @keywords methods
#' @examples
#'
#' \dontrun{
#' ## xpdb5 is an Xpose data object
#' ## We expect to find the required NONMEM run and table files for run
#' ## 5 in the current working directory
#' xpdb5 <- xpose.data(5)
#'
#' xpdb5 <- change.var.name(xpdb5)
#' }
#'
#' @export change.var.name
"change.var.name" <- function(object, classic = FALSE)
{
data <- object
cat("The database contains the following items:\n")
cat(names(object@Data), fill = 60)
cat("\nType the name of the variable you want to change the name of:\n")
ans <- readline()
if(is.na(index <- match(ans, names(data@Data)))) {
cat("The current database does not contain a variable with that name.\n")
return(cat(""))
}
if(is.na(sindex <- match(ans, names(data@SData)))) {
cat("The simulated data does not contain a variable with that name.\n")
}
lindex <- match(ans, names(data@Prefs@Labels))
cat("Type the new name:\n")
ans1 <- readline()
ans1 <- paste(ans1,collapse=" ")
if(!is.na(match(ans1,names(data@Data)))) {
cat("There is already a variable with that name in the current database!\n")
return(cat(""))
}
names(data@Data)[index] <- ans1 # Data
names(data@SData)[sindex] <- ans1 # SData
names(data@Prefs@Labels)[lindex] <- ans1 # Labels
data@Prefs@Xvardef$parms <- replace(data@Prefs@Xvardef$parms, grep(ans, data@Prefs@Xvardef$parms), ans1) # replace in parms
data@Prefs@Xvardef$covariates <- replace(data@Prefs@Xvardef$covariates, grep(ans, data@Prefs@Xvardef$covariates), ans1) # replace in parms
data@Prefs@Xvardef$id <- replace(data@Prefs@Xvardef$id, grep(ans, data@Prefs@Xvardef$id), ans1)
data@Prefs@Xvardef$idv <- replace(data@Prefs@Xvardef$idv, grep(ans, data@Prefs@Xvardef$idv), ans1)
data@Prefs@Xvardef$idlab <- replace(data@Prefs@Xvardef$idlab, grep(ans, data@Prefs@Xvardef$idlab), ans1)
data@Prefs@Xvardef$occ <- replace(data@Prefs@Xvardef$occ, grep(ans, data@Prefs@Xvardef$occ), ans1)
data@Prefs@Xvardef$dv <- replace(data@Prefs@Xvardef$dv, grep(ans, data@Prefs@Xvardef$dv), ans1)
data@Prefs@Xvardef$res <- replace(data@Prefs@Xvardef$res, grep(ans, data@Prefs@Xvardef$res), ans1)
data@Prefs@Xvardef$iwres <- replace(data@Prefs@Xvardef$iwres, grep(ans, data@Prefs@Xvardef$iwres), ans1)
data@Prefs@Xvardef$wres <- replace(data@Prefs@Xvardef$wres, grep(ans, data@Prefs@Xvardef$wres), ans1)
data@Prefs@Xvardef$pred <- replace(data@Prefs@Xvardef$pred, grep(ans, data@Prefs@Xvardef$pred), ans1)
data@Prefs@Xvardef$ipred <- replace(data@Prefs@Xvardef$ipred, grep(ans, data@Prefs@Xvardef$ipred), ans1)
for (i in 1:length(data@Prefs@Labels)) {
data@Prefs@Labels[i] <- replace(data@Prefs@Labels[i], grep(ans, data@Prefs@Labels[i]), ans1)
}
#class(object@Data) <- "data.frame"
#vname(data@Data[,index]) <- ans1
#class(object@Data) <- "xpose"
if (classic==TRUE) {
c1<-call("assign",paste("xpdb", object@Runno, sep = ""), data, immediate=T, envir = .GlobalEnv)
eval(c1)
c2<-call("assign",pos = 1, ".cur.db", eval(as.name(paste("xpdb", object@Runno, sep = ""))))
eval(c2)
return(cat(""))
} else {
return(data)
}
}
| /scratch/gouwar.j/cran-all/cranData/xpose4/R/change.var.name.R |
# Xpose 4
# An R-based population pharmacokinetic/
# pharmacodynamic model building aid for NONMEM.
# Copyright (C) 1998-2004 E. Niclas Jonsson and Mats Karlsson.
# Copyright (C) 2005-2008 Andrew C. Hooker, Justin J. Wilkins,
# Mats O. Karlsson and E. Niclas Jonsson.
# Copyright (C) 2009-2010 Andrew C. Hooker, Mats O. Karlsson and
# E. Niclas Jonsson.
# This file is a part of Xpose 4.
# Xpose 4 is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public License
# as published by the Free Software Foundation, either version 3
# of the License, or (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
# You should have received a copy of the GNU Lesser General Public License
# along with this program. A copy can be cound in the R installation
# directory under \share\licenses. If not, see http://www.gnu.org/licenses/.
#' Changes the label of an Xpose data item
#'
#' This function allows the labels of data items in the Xpose database to be
#' changed.
#'
#' This function facilitates the changing of data item labels in the
#' object@Prefs@Labels slot.
#'
#' @param object An \code{xpose.data} object.
#' @param listall A logical operator specifying whether the items in the
#' database should be listed.
#' @param classic A logical operator specifying whether the function should
#' assume the classic menu system. This is an internal option and need never be
#' called from the command line.
#' @return An \code{\link{xpose.data}} object.
#' @author Justin Wilkins
#' @seealso \code{\link{Data}},\code{\link{SData}},\code{\link{xpose.data}}
#' @keywords methods
#' @examples
#'
#' \dontrun{
#' ## xpdb5 is an Xpose data object
#' ## We expect to find the required NONMEM run and table files for run
#' ## 5 in the current working directory
#' xpdb5 <- xpose.data(5)
#'
#' xpdb5 <- change.xlabel(xpdb5)
#' }
#'
#' @export change.xlabel
"change.xlabel"<-
function(object, listall=TRUE, classic=FALSE)
{
if(listall) {
db.names(object)
}
cat("\nPlease type the name of the variable whose label you\n")
cat("would like to change...\n")
ans <- readline()
dat <- object
if(ans == "NULL" || ans == "null") {
dat@Prefs@Xvardef$idlab <- NULL
c1<-call("assign","object", dat, immediate=T, envir = .GlobalEnv)
eval(c1)
c2<-call("assign",paste("xpdb", object@Runno, sep = ""), dat, immediate=T, envir = .GlobalEnv)
eval(c2)
invisible()
return()
} else {
if(is.na(pmatch(ans, names(dat@Data)))) {
cat("Couldn't find", ans, "in the current database!\n")
Recall(object, listall = F)
} else {
if(ans == 0) {
return()
} else {
cat(paste("The current label for variable ",ans," is '",xlabel(ans, dat),"'.\n", sep=""))
cat("Enter the new one:\n")
labl <- readline()
dat@Prefs@Labels[ans] <- labl
if (classic==TRUE) {
c1<-call("assign",paste("xpdb", object@Runno, sep = ""), data, immediate=T, envir = .GlobalEnv)
eval(c1)
c2<-call("assign",pos = 1, ".cur.db", eval(as.name(paste("xpdb", object@Runno, sep = ""))))
eval(c2)
return(cat(""))
} else {
return(dat)
}
}
}
}
}
| /scratch/gouwar.j/cran-all/cranData/xpose4/R/change.xlabel.R |
# Xpose 4
# An R-based population pharmacokinetic/
# pharmacodynamic model building aid for NONMEM.
# Copyright (C) 1998-2004 E. Niclas Jonsson and Mats Karlsson.
# Copyright (C) 2005-2008 Andrew C. Hooker, Justin J. Wilkins,
# Mats O. Karlsson and E. Niclas Jonsson.
# Copyright (C) 2009-2010 Andrew C. Hooker, Mats O. Karlsson and
# E. Niclas Jonsson.
# This file is a part of Xpose 4.
# Xpose 4 is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public License
# as published by the Free Software Foundation, either version 3
# of the License, or (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
# You should have received a copy of the GNU Lesser General Public License
# along with this program. A copy can be cound in the R installation
# directory under \share\licenses. If not, see http://www.gnu.org/licenses/.
"change.xp.obj"<- function() {
cat("Please enter the run number you want to process (0 = exit): ")
new.runno <- readline()
if(new.runno == 0) return()
## Check if it exists
if(exists(paste("xpdb", new.runno, sep = ""))) {
cat("A matching database was found. Do you want to use it? (y) (r=recreate) ")
ans <- readline()
if(ans == "y" || ans == "") {
##
## Use old
##
c1<-call("assign",pos = 1, ".cur.db", eval(as.name(paste("xpdb",
new.runno, sep = ""))))
eval(c1)
return()
}
}
##
## Recreate
##
newdb <- xpose.data(new.runno)
if(is.null(newdb)) {
cat("No new database read.\n")
return()
} else {
newnam <- paste("xpdb", new.runno, sep = "")
c1<-call("assign",pos=1,newnam,newdb)
eval(c1)
#assign(pos = 1, newnam, newdb)
c1<-call("assign",pos = 1, ".cur.db",newdb )
eval(c1)
}
}
| /scratch/gouwar.j/cran-all/cranData/xpose4/R/change.xp.obj.R |
# Xpose 4
# An R-based population pharmacokinetic/
# pharmacodynamic model building aid for NONMEM.
# Copyright (C) 1998-2004 E. Niclas Jonsson and Mats Karlsson.
# Copyright (C) 2005-2008 Andrew C. Hooker, Justin J. Wilkins,
# Mats O. Karlsson and E. Niclas Jonsson.
# Copyright (C) 2009-2010 Andrew C. Hooker, Mats O. Karlsson and
# E. Niclas Jonsson.
# This file is a part of Xpose 4.
# Xpose 4 is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public License
# as published by the Free Software Foundation, either version 3
# of the License, or (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
# You should have received a copy of the GNU Lesser General Public License
# along with this program. A copy can be cound in the R installation
# directory under \share\licenses. If not, see http://www.gnu.org/licenses/.
#' Change Xpose variable definitions.
#'
#' These functions allow for the changing of Xpose variable definitions like
#' "idv" and "dv". These variable definitions are used to refer to columns of
#' the observed data in a generic way, so that generic plotting functions can
#' be created.
#'
#'
#' @param object An \code{xpose.data} object.
#' @param var The Xpose variable you would like to change or add to the current
#' object. A one-element character vector (e.g. \code{"idv"}). If
#' \code{".ask"} the user will be prompted to input a value.
#' @param def A vector of column names from NONMEM table files
#' (\code{names(object@Data)}) that should be associated with this variable
#' (e.g. \code{c("TIME")}). Multiple values are allowed. If \code{".ask"} the
#' user will be prompted to input values.
#' @param listall Should the function list the database values?
#' @param classic Is the function being used from the classic interface. This
#' is an internal option.
#' @param check.var Should the variables be checked against the current
#' variables in the object?
#' @param \dots Items passed to functions within this function.
#' @return If called from the the command line then this function returns an
#' xpose database. If called from the classic interface this function updates
#' the current xpose database (.cur.db).
#' @section Additional arguments: \strong{The default xpose variables are:\cr}
#' \describe{ \item{id}{Individual identifier column in dataset}
#' \item{idlab}{values used for plotting ID values on data points in plots}
#' \item{occ}{The occasion variable} \item{dv}{The dv variable} \item{pred}{The
#' pred variable} \item{ipred}{The ipred variable} \item{wres}{The wres
#' variable} \item{cwres}{The cwres variable} \item{res}{The res variable}
#' \item{parms}{The parameters in the database} \item{covariates}{The
#' covariates in the database} \item{ranpar}{The random parameters in the
#' database} }
#' @author Andrew Hooker
#' @seealso \code{\link{xvardef}}, \code{\link{xpose.data}}
#' @keywords methods
#' @examples
#'
#' ## Here we load the example xpose database
#' xpdb <- simpraz.xpdb
#'
#' # Change the "id" variable to point to "PRED" in the xpose object
#' xpdb <- change.xvardef(xpdb,var="id",def="PRED")
#'
#' # Check the value of the "id" variable
#' xvardef("id",xpdb)
#'
#' # Change the "idv" variable
#' change.xvardef(xpdb,var="idv") <- "TIME"
#'
#' # Change the covariate scope
#' change.xvardef(xpdb,var="covariates") <- c("SEX","AGE","WT")
#'
#' \dontrun{
#' # Use the interactive capabilities of the function
#' xpdb <- change.xvardef(xpdb)
#' }
#'
#' @export change.xvardef
change.xvardef <-
function(object,
var=".ask", # a one element vector
def=".ask", # a vector (can have mutiple elements)
listall=TRUE,
classic=FALSE,
check.var=FALSE,
...){
if(is.null(def)|is.null(var)){
if(listall) {
db.names(object)
}
}
if(var==".ask"){
tmp.txt <- paste("\nPlease type the name of the xpose",
"variable you would like to change or add.",
"Current variables are (press return to exit without",
"changing):\n")
cat(unlist(strsplit(tmp.txt," ")),fill=60,file="")
##xpose.string.print(tmp.txt)
cat(names(object@Prefs@Xvardef),"\n",fill=60)
var <- readline()
}
if(var==""){
if (classic==TRUE) {
return(cat(""))
} else {
return(object)
}
} else {
if(classic | check.var){
tmp <- is.na(pmatch(var, names(object@Prefs@Xvardef)))
if(tmp) {
cat("Adding", var, "to the current database!\n")
##return(Recall(object, listall = F, var=NULL,def=def,classic=classic,...))
}
}
}
if(!is.null(def)){
if(length(def)== 1 && def==".ask"){
tmp.txt <- paste("\nThe variable",
paste("\"", var, "\"",sep=""),
"is currently associated with the following observed items:\n")
cat(unlist(strsplit(tmp.txt," ")),fill=60,file="")
##xpose.string.print(tmp.txt)
cat(object@Prefs@Xvardef[[var]],fill=60)
tmp.txt <-
paste("\nPlease type the name(s) of the observed items in the database",
"(object@Data) you would like to associate with the xpose",
"variable",paste("\"", var, "\"",sep=""),
"and finish with a blank line.",
"Possible values are",
"(press return to exit without changing, NULL to remove variable):\n")
cat(unlist(strsplit(tmp.txt," ")),fill=60,file="")
##xpose.string.print(tmp.txt)
cat(names(object@Data),"\n",fill=60)
def <- scan(what=character())
}
if(length(def)==0){
if (classic==TRUE) {
return(cat(""))
} else {
return(object)
}
}
}
if(is.null(def) || all(def == "NULL") || all(def == "null")) {
object@Prefs@Xvardef[[var]] <- NULL
} else {
tmp <- is.na(match(def, names(object@Data)))
if(any(tmp)) {
cat("Couldn't find", def[tmp], "in the current database!\n")
return(Recall(object,
listall = F,
var=var,
def=".ask",
classic=classic,
check.var=check.var,
...))
}
object@Prefs@Xvardef[[var]] <- def
}
if (classic==TRUE) {
c1<-call("assign",pos=1, paste("xpdb", object@Runno, sep = ""), object)
eval(c1)
c2<-call("assign",pos = 1, ".cur.db", object)
eval(c2)
return(cat(""))
} else {
return(object)
}
}
#' @describeIn change.xvardef Change the covariate scope of
#' the xpose database object
#' @param value a vector of values
#' @export
"change.xvardef<-" <-
function(object,
var, # a one element vector
listall=FALSE,
classic=FALSE,
check.var=FALSE,
...,
value){
object <- change.xvardef(object,
var=var,
def=value,
listall=listall,
classic=classic,
check.var=check.var,
...)
return(object)
}
| /scratch/gouwar.j/cran-all/cranData/xpose4/R/change.xvardef.R |
check.gamobj <-
function() {
## another function definition
getit <- function()
{
cat("\nYou have to specify the parameter name and the run number",
"of the gam objects you want to plot. The following",
"gam objects are available:\n", fill = 60)
if(.Platform$OS == "windows") {
cat(objects(pattern="gam.xpose*",pos=1),fill=60)
} else {
cat(objects(pattern = "^gam.xpose",pos=1), fill = 60)
}
cat("\nParameter (0 to exit): ")
ans <- readline()
if(ans == 0){
return(ans <- NULL)
}
cat("Run number (0 to exit):")
ans1 <- readline()
if(ans1 == 0){
return(ans1 <- NULL)
}
gobjname <- paste("gam.xpose.", ans, ".", ans1, sep = "")
if(!exists(gobjname, where = 1)) {
cat("\n*There are no object that matches", gobjname,
"\n")
gobjname <- Recall()
}
return(gobjname)
}
##
## The real code starts here
##
if(exists("current.gam", where = 1)) {
cat("\nThe current GAM object is for",
eval(parse(text=paste("current.gam","$pars",sep=""))),
#current.gam$pars,
"in run",
#current.gam$runno,
eval(parse(text=paste("current.gam","$runno",sep=""))),
".\n")
cat("\nDo you want to proceed with this gam object? y(n) ")
ans <- readline()
if(ans != "y" && ans != "") {
gobjname <- getit()
if(!is.null(gobjname)){
c1 <- call("assign",pos = 1, "current.gam", eval(as.name(gobjname)),immediate=T)
eval(c1)
}
} else {
gobjname <- T
}
} else {
gobjname <- getit()
if(!is.null(gobjname)){
c2 <- call("assign",pos=1, "current.gam", eval(as.name(gobjname)),immediate=T)
eval(c2)
}
}
return(gobjname)
}
| /scratch/gouwar.j/cran-all/cranData/xpose4/R/check.gamobj.R |
#' Data functions for Xpose 4
#'
#' These functions perform various tasks in managing Xpose data objects.
#'
#' These are internal Xpose functions, not intended for direct use.
#'
#' @param vars List of variables to be checked.
#' @param object An \code{xpose.data} object.
#' @param silent A logical operator specifying whether output should be
#' displayed.
#' @param filename A filename to be checked for readability.
#' @return TRUE, FALSE or NULL.
#' @author Niclas Jonsson and Andrew Hooker
#' @seealso \code{\link{xpose.prefs-class}}, \code{\link{xvardef}}
#' @keywords internal
check.vars <- function(vars,object,silent=FALSE) {
for (v in vars) {
if(is.null(xvardef(v,object))) {
if(is.na(pmatch(v,names(object@Data)))){
if(!silent) {
cat(paste("\n","-----------Variable(s) not defined!-------------\n",
v, "is/are not defined in the current database\n",
"and must be defined for this command to work!\n",
"------------------------------------------------\n"))
}
return(NULL)
}
}
}
return(TRUE)
}
| /scratch/gouwar.j/cran-all/cranData/xpose4/R/check.vars.R |
sqrtm <- function(x) {
xe <- eigen(x)
xe1 <- xe$values
if(all(xe1 >= 0)) {
xev1 <- diag(sqrt(xe1),nrow=length(xe1))
} else {
i=1
while(i<(length(xe1)+1)){
if(xe1[i]<0){
xe1[i]=0
}
i=i+1
}
xev1 <- diag(sqrt(xe1),nrow=length(xe1))
}
xval1 <- cbind(xe$vectors)
xval1i <- solve(xval1)
y <- xval1 %*% xev1 %*% xval1i
## test with
##foo <- matrix(c(5,-4,1,0,0,-4,6,-4,1,0,1,-4,6,-4,1,0,1,-4,6,-4,0,0,1,-4,5),nrow=5,ncol=5)
##foo1 <- sqrtm(foo)
##foo1
##foo1%*%foo1
##
}
"is.cwres.readable.file" <- function(filename )
{
## If we are not dealing with R -> Splus
if(is.null(version$language)) {
cat("This version of Xpose uses R")
## if(platform() == "WIN386") {
## access(filename, 4) == 0
## } else {
## filename <- paste("'", filename, "'", sep = "")
## sapply(paste("test -f", filename, "-a -r", filename), unix,
## output = F) == 0
## }
} else {
return(file.exists(filename)[1])
}
}
read.cwres.data <-
function(filename,
old.file.convention=FALSE,
est.tab.suffix=".est",
deriv.tab.suffix=".deriv",
...) {
tables.read <- FALSE
if(old.file.convention){
if ((is.cwres.readable.file(paste(filename,".50",sep=""))) &&
##(is.cwres.readable.file(paste(filename,".51",sep=""))) &&
(is.cwres.readable.file(paste(filename,".52",sep=""))) &&
##(is.cwres.readable.file(paste(filename,".53",sep=""))) &&
(is.cwres.readable.file(paste(filename,".54",sep=""))) &&
##(is.cwres.readable.file(paste(filename,".55",sep=""))) &&
(is.cwres.readable.file(paste(filename,".56",sep=""))) &&
##(is.cwres.readable.file(paste(filename,".57",sep=""))) &&
(is.cwres.readable.file(filename))) {
nsim <- 1
num.fields <- count.fields(filename,skip=1)
if((length(unique(num.fields))!=1) ||
## These lines fix problem if num_fields matches fields first header row
(unique(num.fields) == 8) ||
(unique(num.fields) == 3)) {
tmp <- readLines(filename, n = -1)
inds <- grep("TABLE",tmp)
if (length(inds)!=1){
cat("Multiple simulations not supported\n")
cat("using this old file convention\n")
return(NULL)
} else {
data <- read.table(filename,skip=1,header=T)
}
} else {
data <- read.table(filename,skip=1,header=T)
}
size.of.sim <- dim(data)[1]/nsim
data[,"iteration.number"] <- sort(rep(1:nsim,size.of.sim))
eta <- vector("list",nsim)
theta <- vector("list",nsim)
omega <- vector("list",nsim)
sigma <- vector("list",nsim)
##data <- read.table(filename,skip=1,header=TRUE)
eta[[1]] <- read.table(paste(filename,".50",sep=""))
##ofv <- read.table(paste(filename,".51",sep=""))
theta[[1]] <- read.table(paste(filename,".52",sep=""))
##setheta <- read.table(paste(filename,".53",sep=""))
omega[[1]] <- read.table(paste(filename,".54",sep=""))
##seomega <- read.table(paste(filename,".55",sep=""))
sigma[[1]] <- read.table(paste(filename,".56",sep=""))
##sesigma <- read.table(paste(filename,".57",sep=""))
tables.read <- TRUE
}
} else { # new file convention
est.file <- paste(filename,est.tab.suffix,sep="")
deriv.file <- paste(filename,deriv.tab.suffix,sep="")
if ((is.cwres.readable.file(est.file)) &&
(is.cwres.readable.file(deriv.file))) {
nsim <- 1
#########################
## read derivatives table
#########################
## Check if we have unequal number of fields in the derivative file
## used for multiple simulations
num.fields <- count.fields(deriv.file,skip=1)
if((length(unique(num.fields))!=1) ||
## These lines fix problem if num_fields matches fields first header row
(unique(num.fields) == 8) ||
(unique(num.fields) == 3)) {
tmp <- readLines(deriv.file, n = -1)
inds <- grep("TABLE",tmp)
if (length(inds)!=1){
inds <- inds[c(2:length(inds))]
inds2 <- inds+1
tempfile<- paste(deriv.file,".xptmp",sep="")
write.table(tmp[-c(inds,inds2)],file=tempfile,
row.names=FALSE,quote=FALSE)
data <- read.table(tempfile,skip=2,header=T)
unlink(tempfile)
## add iteration label to data
nsim <- length(inds)+1
} else {
data <- read.table(deriv.file,skip=1,header=T)
}
} else {
data <- read.table(deriv.file,skip=1,header=T)
}
size.of.sim <- dim(data)[1]/nsim
data[,"iteration.number"] <- sort(rep(1:nsim,size.of.sim))
#########################
## read estimated parameters table
#########################
filename.extra <- est.file
data.extra <- scan(filename.extra,
sep = "\n", what = character(),
quiet=TRUE)
eta.pat <- "^ *ETAS"
theta.pat <- "^ *THETAS"
omega.pat <- "^ *OMEGAS"
sigma.pat <- "^ *SIGMAS"
eta.pat.line <- grep(eta.pat, data.extra)
theta.pat.line <- grep(theta.pat, data.extra)
omega.pat.line <- grep(omega.pat, data.extra)
sigma.pat.line <- grep(sigma.pat, data.extra)
pat.lines <- list(eta.pat.line,
theta.pat.line,
omega.pat.line,
sigma.pat.line)
pattern.lengths <- sapply(pat.lines,length)
if(!all(pattern.lengths==nsim)){
cat(paste("The",est.file,"and",deriv.file,
"files do not match in size\n"))
return(NULL)
}
eta <- vector("list",nsim)
theta <- vector("list",nsim)
omega <- vector("list",nsim)
sigma <- vector("list",nsim)
for(i in 1:nsim){
tot.eta.rows <- theta.pat.line[i] - eta.pat.line[i] - 1
tot.theta.rows <- omega.pat.line[i] - theta.pat.line[i] - 1
tot.omega.rows <- sigma.pat.line[i] - omega.pat.line[i] - 1
if(i==nsim){
tot.sigma.rows <- length(data.extra) - sigma.pat.line[i]
} else {
tot.sigma.rows <- eta.pat.line[i+1] - sigma.pat.line[i] - 1
}
eta[[i]] <- read.table(filename.extra,skip=eta.pat.line[i],nrows=tot.eta.rows)
theta[[i]] <- read.table(filename.extra,skip=theta.pat.line[i],nrows=tot.theta.rows)
omega[[i]] <- read.table(filename.extra,skip=omega.pat.line[i],nrows=tot.omega.rows)
sigma[[i]] <- read.table(filename.extra,skip=sigma.pat.line[i],nrows=tot.sigma.rows)
}
tables.read <- TRUE
}
} # end new file convention
if (tables.read){
setClass("nm.data",
slots=c(data = "data.frame"
,eta = "data.frame"
##,ofv = "data.frame"
,theta = "data.frame"
##,setheta = "data.frame"
,omega = "data.frame"
##,seomega = "data.frame"
,sigma = "data.frame"
##,sesigma = "data.frame",
),
where = .GlobalEnv
)
all.data <- vector("list",nsim)
for(i in 1:nsim){
for (j in names(eta[[i]])){
if (!is.numeric(eta[[i]][[j]])) {
cat(paste("Some values of ETA in the NONMEM produced file",
filename.extra,
"are non-numeric\n"))
cat("Attempting to fix the problem\n")
## add an 'E' where NONMEM has dropped one
## i.e. if the number is -0.2404305E-105
## NONMEM writes -0.2404305-105
exp.pat <- "([0-9]+)([+-][0-9]+)"
repl.exp.pat <- "\\1E\\2"
#bad.locs <- grep(exp.pat,eta[[i]][[j]])
new.vals <- gsub(exp.pat,repl.exp.pat,eta[[i]][[j]])
eta[[i]][j] <- as.numeric(new.vals)
}
}
all.data[[i]] <- new("nm.data"
,data=data[data$iteration.number==i,]
,eta=eta[[i]]
##,ofv=ofv
,theta=theta[[i]]
##,setheta=setheta
,omega=omega[[i]]
##,seomega=seomega
,sigma=sigma[[i]]
##,sesigma=sesigma
)
}
if(is.null(data$MDV)){
cat("Assuming all dataset lines contain a measurement\n")
cat("No MDV item defined in dataset\n")
}
if(is.null(data$DV)){
dv.found <- FALSE
cat("No DV item defined in dataset\n")
## use this code to det the DV to the value at the position
## just beofre PRED RES and WRES
##
## doesn't work right now!
##
#append.list <- c("PRED","RES","WRES")
#data.names <- names(data)
#tmp.length <- length(data.names)
#if (all(data.names[(tmp.length-3):(tmp.length-1)]==append.list)){
# data[,"DV"]=data[[data.names[(tmp.length-4)]]]
# dv.found <- TRUE
# cat(paste("Using", data.names[(tmp.length-4)],"as the DV value\n"))
#}
if(!dv.found){
all.data <- NULL
}
}
} else { # no tables read
all.data <- NULL
cat("Some or all of the required CWRES tables are\n",
"missing. Please see the online help for details\n",
"of what is required (?compute.cwres).\n")
}
return(all.data)
}
ind.cwres <-
function(ind.data,
H.names,
G.names,
OMEGA,
SIGMA,
IND.ETAS,
...){
if(is.null(ind.data$MDV)){
ind.data1 <- ind.data
} else {
ind.data1 <- ind.data[ind.data$MDV==0,]
}
if (nrow(ind.data1)!=0) {
## for testing
##cat(paste("ID",ind.data1[1,"ID"],"\n"))
## create the epsilon linearization matrix H
H.EPS = as.matrix(subset(ind.data1,select=H.names))
## create the eta linearization matrix G
G.ETA = as.matrix(subset(ind.data1,select=G.names))
## covariance matrix
## this is only true for NON-L2 type data
## L2 data will have the first term non-diagonal
TMP <- diag(H.EPS %*% SIGMA %*% t(H.EPS))
IND.COV = diag(TMP,nrow=length(TMP)) +
G.ETA %*% OMEGA %*% t(G.ETA)
## FOCE residuals
#browser()
if(any(grepl("^IPRED$",names(ind.data1)))) EXP.F <- as.matrix(ind.data1$IPRED) - G.ETA %*% IND.ETAS
if(any(grepl("^IPRE$",names(ind.data1)))) EXP.F <- as.matrix(ind.data1$IPRE) - G.ETA %*% IND.ETAS
#EXP.F <- as.matrix(ind.data1$IPRE) - G.ETA %*% IND.ETAS
FOCE.RES <- as.matrix(ind.data1$DV) - EXP.F
## CWRES
SQRT.IND.COV <- sqrtm(IND.COV)
IND.CWRES <- solve(SQRT.IND.COV,FOCE.RES)
## add zero values back again
if(is.null(ind.data$MDV)){
} else {
CWRES <- rep(0,length(ind.data[,1]))
ind.data2 <- cbind(ind.data,CWRES)
ind.data2[ind.data2$MDV==0,"CWRES"] <- IND.CWRES
IND.CWRES <- as.matrix(ind.data2["CWRES"])
}
}
else {
CWRES <- rep(0, length(ind.data[, 1]))
ind.data2 <- cbind(ind.data, CWRES)
IND.CWRES <- as.matrix(ind.data2["CWRES"])
}
return(IND.CWRES)
}
#' Compute the Conditional Weighted Residuals
#'
#' This function computes the conditional weighted residuals (CWRES) from a
#' NONMEM run. CWRES are an extension of the weighted residuals (WRES), but
#' are calculated based on the first-order with conditional estimation (FOCE)
#' method of linearizing a pharmacometric model (WRES are calculated based on
#' the first-order (FO) method). The function requires a NONMEM table file and
#' an extra output file that must be explicitly asked for when running NONMEM,
#' see details below.
#'
#' The function reads in the following two
#' files:
#'
#' \code{paste(tab.prefix,run.number,sim.suffix,est.tab.suffix,sep="")}
#'
#' \code{paste(tab.prefix,run.number,sim.suffix,deriv.tab.suffix,sep="")}
#'
#' Which might be for example:
#'
#' \preformatted{ cwtab1.est cwtab1.deriv }
#'
#' and (depending on the input values to the function) returns the CWRES in
#' vector form as well as creating a new table file named:
#'
#' \code{ paste(tab.prefix,run.number,sim.suffix,sep="") }
#'
#' Which might be for example:
#'
#' \preformatted{ cwtab1 }
#'
#' @aliases compute.cwres ind.cwres read.cwres.data is.cwres.readable.file
#' sqrtm xpose.calculate.cwres
#' @param run.number The run number of the NONMEM from which the CWRES are to
#' be calculated.
#' @param tab.prefix The prefix to two NONMEM file containing the needed values
#' for the computation of the CWRES, described in the details section.
#' @param sim.suffix The suffix ,before the ".", of the NONMEM file containing
#' the needed values for the computation of the CWRES, described in the details
#' section. For example, the table files might be named \code{cwtab1sim.est}
#' and \code{cwtab1sim.deriv}, in which case \code{sim.suffix="sim"}.
#' @param est.tab.suffix The suffix, after the ".", of the NONMEM file
#' containing the estimated parameter values needed for the CWRES calculation.
#' @param deriv.tab.suffix The suffix, after the ".", of the NONMEM file
#' containing the derivatives of the model with respect to the random
#' parameters needed for the CWRES calculation.
#' @param old.file.convention For backwards compatibility. Use this if you are
#' using the previous file convention for CWRES (table files named cwtab1,
#' cwtab1.50, cwtab1.51, ... , cwtab.58 for example).
#' @param id Can be either "ALL" or a number matching an ID label in the
#' \code{datasetname}. Value is fixed to "ALL" for
#' \code{xpose.calculate.cwres}.
#' @param printToOutfile Logical (TRUE/FALSE) indicating whether the CWRES
#' values calculated should be appended to a copy of the \code{datasetname}.
#' Only works if \code{id}="ALL". If chosen the resulting output file will be
#' \code{datasetname}.cwres. Value is fixed to TRUE for
#' \code{xpose.calculate.cwres}.
#' @param onlyNonZero Logical (TRUE/FALSE) indicating if the return value (the
#' CWRES values) of \code{compute.cwres} should include the zero values
#' associated with non-measurement lines in a NONMEM data file.
#' @param object An xpose.data object.
#' @param cwres.table.prefix The prefix to the NONMEM table file containing the
#' derivative of the model with respect to the etas and epsilons, described in
#' the details section.
#' @param tab.suffix The suffix to the NONMEM table file containing the
#' derivative of the model with respect to the etas and epsilons, described in
#' the details section.
#' @param classic Indicates if the function is to be used in the classic menu
#' system.
#' @param \dots Other arguments passed to basic functions in code.
#' @return \describe{\item{compute.cwres}{Returns a vector containing the values of the
#' CWRES.} \item{xpose.calculate.cwres}{ Returns an Xpose data object that
#' contains the CWRES. If simulated data is present, then the CWRES will also
#' be calculated for that data.}}
#'
#'
#' @section Setting up the NONMEM model file:
#' In order for this function to
#' calculate the CWRES, NONMEM must be run while requesting certain tables and
#' files to be created. How these files are created differs depending on if
#' you are using $PRED or ADVAN as well as the version of NONMEM you are using.
#' These procedures are known to work for NONMEM VI but may be different for
#' NONMEM V and NONMEM VII. We have attempted to indicate where NONMEM V may be different,
#' but this has not been extensively tested! For NONMEM VII the CWRES are calculated internally
#' so this function is rarely needed.
#'
#' This procedure can be done automatically using Perl Speaks NONMEM (PsN) and
#' we highly recommend using PsN for this purpose. After installing PsN just
#' type '\code{execute [modelname] -cwres}'. See
#' \url{https://uupharmacometrics.github.io/PsN/} for more details.
#'
#' There are five main insertions needed in your NONMEM control file:
#' \enumerate{ \item$ABB COMRES=X.
#'
#' Insert this line directly after your $DATA line. The value of X is the
#' number of ETA() terms plus the number of EPS() terms in your model. For
#' example for a model with three ETA() terms and two EPS() terms the code
#' would look like this:
#'
#' \preformatted{$DATA temp.csv IGNORE=@
#' $ABB COMRES=5
#' $INPUT ID TIME DV MDV AMT EVID
#' $SUB ADVAN2 TRANS2} % preformatted % item
#'
#' \item Verbatim code.
#'
#' \itemize{ \item Using ADVAN.
#'
#' If you are using ADVAN routines in your model, then Verbatim code should be
#' inserted directly after the $ERROR section of your model file. The length
#' of the code depends again on the number of ETA() terms and EPS() terms in
#' your model. For each ETA(y) in your model there is a corresponding term
#' G(y,1) that you must assign to a COM() variable. For each EPS(y) in your
#' model, there is a corresponding HH(y,1) term that you must assign to a COM()
#' variable.
#'
#' For example for a model using ADVAN routines with three ETA() terms and two
#' EPS() terms the code would look like this:
#'
#' \preformatted{
#' "LAST
#' " COM(1)=G(1,1)
#' " COM(2)=G(2,1)
#' " COM(3)=G(3,1)
#' " COM(4)=HH(1,1)
#' " COM(5)=HH(2,1)
#' } % preformatted
#'
#'
#' \item Using PRED.
#'
#' If you are using $PRED, the verbatim code should be inserted directly after
#' the $PRED section of your model file. For each ETA(y) in your model there
#' is a corresponding term G(y,1) that you must assign to a COM() variable.
#' For each EPS(y) in your model, there is a corresponding H(y,1) term that you
#' must assign to a COM() variable. The code would look like this for three
#' ETA() terms and two EPS() terms:
#'
#' \preformatted{
#' "LAST
#' " COM(1)=G(1,1)
#' " COM(2)=G(2,1)
#' " COM(3)=G(3,1)
#' " COM(4)=H(1,1)
#' " COM(5)=H(2,1)
#' } % preformatted
#'
#' } % itemize
#'
#'
#' \item INFN routine.
#'
#' \itemize{ \item Using ADVAN with NONMEM VI and higher.
#'
#' If you are using ADVAN routines in your model, then an $INFN section should
#' be placed directly after the $PK section using the following code. In this
#' example we are assuming that the model file is named something like
#' 'run1.mod', thus the prefix to these file names 'cwtab' has the same run
#' number attached to it (i.e. 'cwtab1'). This should be changed for each new
#' run number.
#'
#' \preformatted{$INFN
#' IF (ICALL.EQ.3) THEN
#' OPEN(50,FILE='cwtab1.est')
#' WRITE(50,*) 'ETAS'
#' DO WHILE(DATA)
#' IF (NEWIND.LE.1) WRITE (50,*) ETA
#' ENDDO
#' WRITE(50,*) 'THETAS'
#' WRITE(50,*) THETA
#' WRITE(50,*) 'OMEGAS'
#' WRITE(50,*) OMEGA(BLOCK)
#' WRITE(50,*) 'SIGMAS'
#' WRITE(50,*) SIGMA(BLOCK)
#' ENDIF
#' } % preformatted
#'
#'
#' \item Using ADVAN with NONMEM V.
#'
#' If you are using ADVAN routines in your model, then you need to use an INFN
#' subroutine. If we call the INFN subroutine 'myinfn.for' then the $SUBS line
#' of your model file should include the INFN option. That is, if we are using
#' ADVAN2 and TRANS2 in our model file then the $SUBS line would look like:
#'
#' \preformatted{$SUB ADVAN2 TRANS2 INFN=myinfn.for} % preformatted
#'
#' The 'myinfn.for' routine for 4 thetas, 3 etas and 1 epsilon is shown below.
#' If your model has different numbers of thetas, etas and epsilons then the
#' values of NTH, NETA, and NEPS, should be changed respectively. These vales
#' are found in the DATA statement of the subroutine. additionally, in this
#' example we are assuming that the model file is named something like
#' 'run1.mod', thus the prefix to the output file names ('cwtab') in this
#' subroutine has the same run number attached to it (i.e. 'cwtab1'). This
#' number should be changed for each new run number (see the line beginning
#' with 'OPEN').
#' %Please note that the 4th and 5th lines of code should be one
#' %line with the '...' removed from each line, reading: \code{COMMON /ROCM6/
#' %THETAF(40),OMEGAF(30,30),SIGMAF(30,30)}.
#'
#'
#' \preformatted{
#' SUBROUTINE INFN(ICALL,THETA,DATREC,INDXS,NEWIND)
#' DIMENSION THETA(*),DATREC(*),INDXS(*)
#' DOUBLE PRECISION THETA
#' COMMON /ROCM6/ THETAF(40),OMEGAF(30,30),SIGMAF(30,30)
#' COMMON /ROCM7/ SETH(40),SEOM(30,30),SESIG(30,30)
#' COMMON /ROCM8/ OBJECT
#' COMMON /ROCM9/ IERE,IERC
#' DOUBLE PRECISION THETAF, OMEGAF, SIGMAF
#' DOUBLE PRECISION OBJECT
#' REAL SETH,SEOM,SESIG
#' DOUBLE PRECISION ETA(10)
#' INTEGER J,I
#' INTEGER IERE,IERC
#' INTEGER MODE
#' INTEGER NTH,NETA,NEPS
#' DATA NTH,NETA,NEPS/4,3,1/
#' IF (ICALL.EQ.0) THEN
#' C open files here, if necessary
#' OPEN(50,FILE='cwtab1.est')
#' ENDIF
#' IF (ICALL.EQ.3) THEN
#' MODE=0
#' CALL PASS(MODE)
#' MODE=1
#' WRITE(50,*) 'ETAS'
#' 20 CALL PASS(MODE)
#' IF (MODE.EQ.0) GO TO 30
#' IF (NEWIND.NE.2) THEN
#' CALL GETETA(ETA)
#' WRITE (50,97) (ETA(I),I=1,NETA)
#' ENDIF
#' GO TO 20
#' 30 CONTINUE
#' WRITE (50,*) 'THETAS'
#' WRITE (50,99) (THETAF(J),J=1,NTH)
#' WRITE(50,*) 'OMEGAS'
#' DO 7000 I=1,NETA
#' 7000 WRITE (50,99) (OMEGAF(I,J),J=1,NETA)
#' WRITE(50,*) 'SIGMAS'
#' DO 7999 I=1,NEPS
#' 7999 WRITE (50,99) (SIGMAF(I,J),J=1,NEPS)
#' ENDIF
#' 99 FORMAT (20E15.7)
#' 98 FORMAT (2I8)
#' 97 FORMAT (10E15.7)
#' RETURN
#' END
#' } % preformatted
#'
#' \item Using $PRED with NONMEM VI and higher.
#'
#' If you are using $PRED, then an the following code should be placed at the
#' end of the $PRED section of the model file (together with the verbatim
#' code). In this example we are assuming that the model file is named
#' something like 'run1.mod', thus the prefix to these file names 'cwtab' has
#' the same run number attached to it (i.e. 'cwtab1'). This should be changed
#' for each new run number.
#'
#' \preformatted{IF (ICALL.EQ.3) THEN
#' OPEN(50,FILE='cwtab1.est')
#' WRITE(50,*) 'ETAS'
#' DO WHILE(DATA)
#' IF (NEWIND.LE.1) WRITE (50,*) ETA
#' ENDDO
#' WRITE(50,*) 'THETAS'
#' WRITE(50,*) THETA
#' WRITE(50,*) 'OMEGAS'
#' WRITE(50,*) OMEGA(BLOCK)
#' WRITE(50,*) 'SIGMAS'
#' WRITE(50,*) SIGMA(BLOCK)
#' ENDIF
#' } % preformatted
#'
#' \item Using $PRED with NONMEM V.
#'
#' If you are using $PRED with NONMEM V, then you need to add verbatim code
#' immediately after the $PRED command. In this example we assume 4 thetas, 3
#' etas and 1 epsilon. If your model has different numbers of thetas, etas and
#' epsilons then the values of NTH, NETA, and NEPS, should be changed
#' respectively. These vales are found in the DATA statement below.
#' %Please
#' %note that the 3rd and 4th lines of code should be one line with the '...'
#' %removed from each line, reading: \code{\" COMMON /ROCM6/
#' %THETAF(40),OMEGAF(30,30),SIGMAF(30,30) }.
#'
#' \preformatted{
#' $PRED
#' "FIRST %"
#' " COMMON /ROCM6/ THETAF(40),OMEGAF(30,30),SIGMAF(30,30)
#' " COMMON /ROCM7/ SETH(40),SEOM(30,30),SESIG(30,30)
#' " COMMON /ROCM8/ OBJECT
#' " DOUBLE PRECISION THETAF, OMEGAF, SIGMAF
#' " DOUBLE PRECISION OBJECT
#' " REAL SETH,SEOM,SESIG
#' " INTEGER J,I
#' " INTEGER MODE
#' " INTEGER NTH,NETA,NEPS
#' " DATA NTH,NETA,NEPS/4,3,1/
#' } % preformatted
#' After this verbatim code you add all of the abbreviated code needed for the
#' $PRED routine in your model file. After the abbreviated code more verbatim
#' code is needed. This verbatim code should be added before the verbatim code
#' discussed above under point 2. In the example below we are assuming that
#' the model file is named something like 'run1.mod', thus the prefix to the
#' output file names ('cwtab') has the same run number attached to it (i.e.
#' 'cwtab1'). This number should be changed for each new run number (see the
#' line beginning with 'OPEN').
#'
#' \preformatted{
#' " IF (ICALL.EQ.0) THEN
#' "C open files here, if necessary
#' " OPEN(50,FILE='cwtab1.est')
#' " ENDIF
#' " IF (ICALL.EQ.3) THEN
#' " MODE=0
#' " CALL PASS(MODE)
#' " MODE=1
#' " WRITE(50,*) 'ETAS'
#' "20 CALL PASS(MODE)
#' " IF (MODE.EQ.0) GO TO 30
#' " IF (NEWIND.NE.2) THEN
#' " CALL GETETA(ETA)
#' " WRITE (50,97) (ETA(I),I=1,NETA)
#' " ENDIF
#' " GO TO 20
#' "30 CONTINUE
#' " WRITE (50,*) 'THETAS'
#' " WRITE (50,99) (THETAF(J),J=1,NTH)
#' " WRITE (50,*) 'OMEGAS'
#' " DO 7000 I=1,NETA
#' "7000 WRITE (50,99) (OMEGAF(I,J),J=1,NETA)
#' " WRITE (50,*) 'SIGMAS'
#' " DO 7999 I=1,NEPS
#' "7999 WRITE (50,99) (SIGMAF(I,J),J=1,NEPS)
#' " ENDIF
#' "99 FORMAT (20E15.7)
#' "98 FORMAT (2I8)
#' "97 FORMAT (10E15.7)
#' } % preformatted
#'
#' } % itemize % item (infn)
#'
#' \item cwtab*.deriv table file.
#'
#' A special table file needs to be created to print out the values contained
#' in the \code{COMRES} variables. In addition the \code{ID, IPRED, MDV, DV,
#' PRED and RES} data items are needed for the computation of the CWRES. The
#' following code should be added to the NONMEM model file. In this example we
#' continue to assume that we are using a model with three ETA() terms and two
#' EPS() terms, extra terms should be added for new ETA() and EPS() terms in
#' the model file. We also assume the model file is named something like
#' 'run1.mod', thus the prefix to these file names 'cwtab' has the same run
#' number attached to it (i.e. 'cwtab1'). This should be changed for each new
#' run number.
#'
#' \preformatted{
#' $TABLE ID COM(1)=G11 COM(2)=G21 COM(3)=G31 COM(4)=H11 COM(5)=H21
#' IPRED MDV NOPRINT ONEHEADER FILE=cwtab1.deriv
#' } % preformatted
#'
#'
#' \item $ESTIMATION.
#'
#' To compute the CWRES, the NONMEM model file must use (at least) the FO
#' method with the \code{POSTHOC} step. If the FO method is used and the
#' \code{POSTHOC} step is not included then the CWRES values will be equivalent
#' to the WRES. The CWRES calculations are based on the FOCE approximation,
#' and consequently give an idea of the ability of the FOCE method to fit the
#' model to the data. If you are using another method of parameter estimation
#' (e.g. FOCE with interaction), the CWRES will not be calculated based on the
#' same model linearization procedure.
#'
#'
#'
#'
#' } % Enumerate
#' @author Andrew Hooker
#' @references Hooker AC, Staatz CE, Karlsson MO. \emph{Conditional weighted
#' residuals, an improved model diagnostic for the FO/FOCE methods}. PAGE 15
#' (2006) Abstr 1001 [\url{http://www.page-meeting.org/?abstract=1001}].
#'
#' Hooker AC, Staatz CE and Karlsson MO, Conditional weighted residuals (CWRES):
#' a model diagnostic for the FOCE method, Pharm Res, 24(12): p. 2187-97, 2007,
#' [\doi{10.1007/s11095-007-9361-x}].
#'
#' @keywords methods
#' @examples
#'
#' \dontrun{
#' ## Capture CWRES from cwtab5.est and cwtab5.deriv
#' cwres <- compute.cwres(5)
#' mean(cwres)
#' var(cwres)
#'
#' ## Capture CWRES from cwtab1.est and cwtab1.deriv, do not print out, allow zeroes
#' cwres <- compute.cwres("1", printToOutFile = FALSE,
#' onlyNonZero = FALSE)
#'
#' ## Capture CWRES for ID==1
#' cwres.1 <- compute.cwres("1", id=1)
#'
#' ## xpdb5 is an Xpose data object
#' ## We expect to find the required NONMEM run and table files for run
#' ## 5 in the current working directory
#' xpdb5 <- xpose.data(5)
#'
#' ## Compare WRES, CWRES
#' xpdb5 <- xpose.calculate.cwres(xpdb5)
#' cwres.wres.vs.idv(xpdb5)
#'
#' }
#'
#' @export
#' @family data functions
compute.cwres <-
function(run.number,
tab.prefix="cwtab",
sim.suffix="",
est.tab.suffix=".est",
deriv.tab.suffix=".deriv",
old.file.convention=FALSE,
id="ALL",
printToOutfile=TRUE,
onlyNonZero=TRUE,
...){
out.file = paste(tab.prefix,run.number,sim.suffix,sep="")
full.dataset <- read.cwres.data(out.file,
old.file.convention=old.file.convention,
est.tab.suffix=est.tab.suffix,
deriv.tab.suffix=deriv.tab.suffix,
...)
if (is.null(full.dataset)) {
return()
}
num.reps <- length(full.dataset)
tot.cwres <- c()
for(rep in 1:num.reps){
## get one of the repetitions
dataset <- full.dataset[[rep]]
## dataset <- read.cwres.data("sdtab1") # only for testing
first.only.data <- dataset@data[!duplicated(dataset@data$ID),]
all.etas <- dataset@eta
all.etas <- cbind(first.only.data["ID"], all.etas)
## create OMEGA, SIGMA matricies
OMEGA <- as.matrix(dataset@omega)
SIGMA <- as.matrix(dataset@sigma)
## create the names of the H and G columns in the dataset
H.names = c()
i=1
while(i<(length(dataset@sigma)+1)){
H.names = c(H.names,paste("H",i,"1",sep=""))
i=i+1
}
G.names = c()
i=1
while(i<(length(dataset@omega)+1)){
G.names = c(G.names,paste("G",i,"1",sep=""))
i=i+1
}
if(id=="ALL"){
id.vals <- unique(dataset@data$ID)
CWRES <- c()
for(i in id.vals){
#browser()
#ind.data <- subset(dataset@data,ID==i)
ind.data <- dataset@data[dataset@data$ID==i,]
ind.etas <- t(as.matrix(all.etas[all.etas$ID==i,colnames(all.etas)!="ID"]))
CWRESI <- ind.cwres(ind.data,
H.names,
G.names,
OMEGA,
SIGMA,
ind.etas,
...)
CWRES <- c(CWRES,CWRESI)
}
CWRES <- as.matrix(CWRES)
if(printToOutfile==TRUE){
## set up out file name
if(old.file.convention){
filename <- paste(out.file,".cwres",sep="")
} else {
filename <- out.file
}
## bind CWRES to data file
#data.cwres <- cbind(dataset@data,CWRES)
data.cwres <- data.frame("ID"=dataset@data$ID)
if(!is.null(dataset@data$MDV)) data.cwres$MDV=dataset@data$MDV
if(!is.null(dataset@data$DV)) data.cwres$DV=dataset@data$DV
if(any(grepl("^IPRE$",names(dataset@data)))){
if(!is.null(dataset@data$IPRE)) data.cwres$IPRE=dataset@data$IPRE
}
if(any(grepl("^IPRED$",names(dataset@data)))){
if(!is.null(dataset@data$IPRED)) data.cwres$IPRED=dataset@data$IPRED
}
if(!is.null(dataset@data$WRES)) data.cwres$WRES=dataset@data$WRES
if(!is.null(CWRES)) data.cwres$CWRES=CWRES
## data.cwres <- data.frame("ID"=dataset@data$ID,
## "DV"=dataset@data$DV,
## "MDV"=dataset@data$MDV,
## "IPRE"=dataset@data$IPRE,
## "WRES"=dataset@data$WRES,
## "CWRES"=CWRES)
## print out dataset
tmp <- installed.packages(priority="NA")
if (length(grep("xpose4",tmp))>0){
xpose.version <- tmp["xpose4","Version"]
xpose.text <- paste("from Xpose version",xpose.version,sep=" ")
} else {
xpose.text <- ""
}
if (rep==1) {
append.table.message <- FALSE
} else {
append.table.message <- TRUE
}
cat(paste("TABLE for CWRES computed using compute.cwres.R",xpose.text,"on",
format(Sys.time(), "%a %b %d, %X, %Y"),"\n"),
file=filename,
append=append.table.message)
newdata <- format(data.cwres,sci=TRUE)
suppressWarnings(
write.table(newdata,filename,row.names=FALSE,sep=" ",
quote=FALSE,append=TRUE)
)
} # end print to out file
if(onlyNonZero==TRUE){
if(is.null(dataset@data$MDV)){
} else {
## bind the data to the data file
data.cwres <- cbind(dataset@data,CWRES)
tmp <- data.cwres[data.cwres$MDV==0,]
#tmp <- subset(data.cwres,MDV==0)
CWRES <- tmp$CWRES
}
}
} else { ## end if ID==ALL
data1 <- dataset@data[dataset@data$ID==id,]
ind.etas <- t(as.matrix(all.etas[all.etas$ID==id,colnames(all.etas)!="ID"]))
CWRES <- ind.cwres(data1,
H.names,
G.names,
OMEGA,
SIGMA,
ind.etas,
...)
if(onlyNonZero==TRUE){
if(is.null(data1$MDV)){
} else {
## bind the data to the data file
data1.cwres <- cbind(data1,CWRES)
tmp <- data1.cwres[data1.cwres$MDV==0,]
#tmp <- subset(data1.cwres,MDV==0)
CWRES <- tmp$CWRES
}
}
} # end if ID=id
tot.cwres <- c(tot.cwres,CWRES)
}# end num.reps
return(tot.cwres)
}
| /scratch/gouwar.j/cran-all/cranData/xpose4/R/compute.cwres.R |
# Xpose 4
# An R-based population pharmacokinetic/
# pharmacodynamic model building aid for NONMEM.
# Copyright (C) 1998-2004 E. Niclas Jonsson and Mats Karlsson.
# Copyright (C) 2005-2008 Andrew C. Hooker, Justin J. Wilkins,
# Mats O. Karlsson and E. Niclas Jonsson.
# Copyright (C) 2009-2010 Andrew C. Hooker, Mats O. Karlsson and
# E. Niclas Jonsson.
# This file is a part of Xpose 4.
# Xpose 4 is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public License
# as published by the Free Software Foundation, either version 3
# of the License, or (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
# You should have received a copy of the GNU Lesser General Public License
# along with this program. A copy can be cound in the R installation
# directory under \share\licenses. If not, see http://www.gnu.org/licenses/.
#' @rdname addid
"computePI" <-
function(x,y,object,limits=object@[email protected]$PIlimits,
logy=FALSE,logx=FALSE,onlyfirst=FALSE,
inclZeroWRES=FALSE,PI.subset=NULL,subscripts) {
iter <- c()
## this prediction interval should be from data passed by the calling function
## should not be computed here!
#data <- SData(object,inclZeroWRES=inclZeroWRES,onlyfirst=onlyfirst,subset=PI.subset)
data <- SData(object,inclZeroWRES=inclZeroWRES,onlyfirst=onlyfirst)
#data <- dplyr::as_data_frame(data)
if(packageVersion("tibble") < "2.0.0"){
data <- tibble::as_data_frame(data)
} else {
data <- tibble::as_tibble(data)
}
if(!is.null(PI.subset)) data <- dplyr::filter(data,PI.subset)
n_iter <- max(data$iter)
n_row <- nrow(dplyr::filter(data, iter==1))
subscripts_2 <- NULL
for(i in 1:n_iter){
subscripts_2 <- c(subscripts_2,subscripts+(n_row)*(i-1))
}
data <- dplyr::slice(data,subscripts_2)
data <- data.frame(data)
if(is.null(data)) return(NULL)
## x is not in data
if(!any(names(data)==x)) {
return(NULL)
}
## y is not in data
if(!any(names(data)==y)) {
return(NULL)
}
if(logy) data[,y] <- log10(data[,y])
data <- data[order(data[,x]),]
## Find the number of intervals
tids <- data[,x]
tims <- unique(tids)
nint <- 12
if(length(tims) <= 12) nint <- length(tims)-1
bins <- eq.xpose(tids,number=nint,overlap=0)
## Add bin indicator to data set
data[,"bin"] <- rep(0,nrow(data))
for(b in 1:nint) {
#cat(b,bins$lower[b],"-",bins$upper[b],"\n")
if(b == 1) {
data[,"bin"] <- ifelse(tids <= bins$upper[b],b,data[,"bin"])
} else {
data[,"bin"] <- ifelse(tids >bins$lower[b] & tids <=bins$upper[b],b,data[,"bin"])
}
}
qua <- sapply(1:nint,function(xx,dat)
{quantile(dat[dat[,"bin"]==xx,y],probs=limits)},data)
qua <- data.frame(t(qua))
names(qua) <- c("lower","upper")
qua$median <- sapply(1:nint,function(xx,dat)
{median(dat[dat[,"bin"]==xx,y])},data)
qua$mean <- sapply(1:nint,function(xx,dat)
{mean(dat[dat[,"bin"]==xx,y])},data)
qua$Xmiddle <- bins$middle
qua$Xlower <- bins$lower
qua$Xupper <- bins$upper
return(qua[!is.na(qua[,1]),])
}
| /scratch/gouwar.j/cran-all/cranData/xpose4/R/computePI.R |
#' @rdname categorical.table
continuous.table <- function(object,
vars,
onlyfirst=TRUE,
subset=xsubset(object),
inclZeroWRES=FALSE,
miss=object@Prefs@Miss) # can be a number
{
data <- Data(object,onlyfirst=onlyfirst,subset=subset,inclZeroWRES=inclZeroWRES)
usemiss <- FALSE
for (nam in vars) {
if(any(is.na(data[[nam]]) | data[[nam]]==miss)) {
usemiss <- TRUE
}
}
if (usemiss == TRUE) {
ret.mat <- matrix(0,ncol=9,nrow=1+length(vars))
ret.mat[1,] <- c("","Mean","SD","Q1","Median","Q3","Range","N","Missing")
} else {
ret.mat <- matrix(0,ncol=8,nrow=1+length(vars))
ret.mat[1,] <- c("","Mean","SD","Q1","Median","Q3","Range","N")
}
i <- 1
for(nam in vars) {
i <- i+1
micov <- subset(data[[nam]], is.na(data[[nam]]) | data[[nam]]==miss)
nomicov<- subset(data[[nam]], !is.na(data[[nam]]) & data[[nam]]!=miss)
suma <- summary(nomicov)[c(4,2,3,5,6,1)]
if (usemiss==TRUE) {
ret.mat[i,] <- c(nam,
suma[1],
signif(sd(nomicov), digits=4),
suma[2:4],
paste(suma[6],"-",suma[5],sep=""),
length(nomicov),
paste(length(micov)," (",
sprintf("%.1f",
100*length(micov)/(length(micov)+length(nomicov))),
"%)",sep="")
)
} else {
ret.mat[i,] <- c(nam,
suma[1],
signif(sd(nomicov), digits=4),
suma[2:4],
paste(suma[6],"-",suma[5],sep=""),
length(nomicov)
)
}
}
class(ret.mat) <- "char.matrix"
return(ret.mat)
}
| /scratch/gouwar.j/cran-all/cranData/xpose4/R/continuous.table.R |
#' Plot the parameter or covariate distributions using a histogram
#'
#' These functions plot the parameter or covariate values stored in an Xpose
#' data object using histograms.
#'
#' Each of the parameters or covariates in the Xpose data object, as specified
#' in \code{object@Prefs@Xvardef$parms}, \code{object@Prefs@Xvardef$covariates}
#' or \code{object@Prefs@Xvardef$ranpar} is evaluated in turn, creating a stack
#' of histograms.
#'
#' A wide array of extra options controlling histograms are available. See
#' \code{\link{xpose.plot.histogram}} for details.
#'
#' @param object An xpose.data object.
#' @param onlyfirst Logical value indicating if only the first row per
#' individual is included in the plot.
#' @param main The title of the plot. If \code{"Default"} then a default title
#' is plotted. Otherwise the value should be a string like \code{"my title"} or
#' \code{NULL} for no plot title.
#' @param \dots Other arguments passed to \code{\link{xpose.plot.histogram}}.
#' @return Delivers a stack of histograms.
#' @author Andrew Hooker & Justin Wilkins
#' @seealso \code{\link{xpose.plot.histogram}},
#' \code{\link{xpose.panel.histogram}}, \code{\link[lattice]{histogram}},
#' \code{\link{xpose.data-class}}, \code{\link{xpose.prefs-class}}
#' @keywords methods
#' @examples
#'
#' ## Here we load the example xpose database
#' xpdb <- simpraz.xpdb
#'
#' ## Parameter histograms
#' parm.hist(xpdb)
#'
#' ## Covariate distribution, in green
#' cov.hist(xpdb, hicol=11, hidcol="DarkGreen", hiborder="White")
#'
#' ## Random parameter histograms
#' ranpar.hist(xpdb)
#'
#' @name par_cov_hist
#' @family specific functions
NULL
#' @describeIn par_cov_hist Covariate distributions
#' @export
cov.hist <-
function(object,
onlyfirst=TRUE,
main="Default",
...) {
if(any(is.null(xvardef("covariates",object)))) {
return(cat("No covariates defined in the current database!\n"))
}
## create enpty list for plots
number.of.plots <- 0
for (i in xvardef("covariates", object)) {
number.of.plots <- number.of.plots + 1
}
plotList <- vector("list",number.of.plots)
plot.num <- 0 # initialize plot number
## loop
for (i in xvardef("covariates", object)) {
xplot <- xpose.plot.histogram(i,
object,
main=NULL,
onlyfirst = onlyfirst,
pass.plot.list=TRUE,
...)
plot.num <- plot.num+1
plotList[[plot.num]] <- xplot
}
default.plot.title <- "Distribution of covariates"
plotTitle <- xpose.multiple.plot.title(object=object,
plot.text = default.plot.title,
main=main,
...)
obj <- xpose.multiple.plot(plotList,plotTitle,...)
return(obj)
}
| /scratch/gouwar.j/cran-all/cranData/xpose4/R/cov.hist.R |
#' Plot the parameter or covariate distributions using quantile-quantile (Q-Q)
#' plots
#'
#' These functions plot the parameter or covariate values stored in an Xpose
#' data object using Q-Q plots.
#'
#' Each of the parameters or covariates in the Xpose data object, as specified
#' in \code{object@Prefs@Xvardef$parms}, \code{object@Prefs@Xvardef$ranpar} or
#' \code{object@Prefs@Xvardef$covariates}, is evaluated in turn, creating a
#' stack of Q-Q plots.
#'
#' A wide array of extra options controlling Q-Q plots are available. See
#' \code{\link{xpose.plot.qq}} for details.
#'
#' @param object An xpose.data object.
#' @param onlyfirst Logical value indicating if only the first row per
#' individual is included in the plot.
#' @param main The title of the plot. If \code{"Default"} then a default title
#' is plotted. Otherwise the value should be a string like \code{"my title"} or
#' \code{NULL} for no plot title.
#' @param \dots Other arguments passed to \code{\link{xpose.plot.qq}}.
#' @return Delivers a stack of Q-Q plots.
#' @author Andrew Hooker & Justin Wilkins
#' @seealso \code{\link{xpose.plot.qq}}, \code{\link{xpose.panel.qq}},
#' \code{\link[lattice]{qqmath}}, \code{\link{xpose.data-class}},
#' \code{\link{xpose.prefs-class}}
#' @keywords methods
#' @examples
#'
#' ## Here we load the example xpose database
#' xpdb <- simpraz.xpdb
#'
#' ## parameter histograms
#' parm.qq(xpdb)
#'
#' ## A stack of random parameter histograms
#' ranpar.qq(xpdb)
#'
#' ## Covariate distribution, in green with red line of identity
#' cov.qq(xpdb, col=11, ablcol=2)
#'
#' @name par_cov_qq
#' @family specific functions
NULL
#' @describeIn par_cov_qq Covariate distributions
#' @export
cov.qq <-
function(object,
onlyfirst=TRUE,
main="Default",
...) {
## is everything in place?
if(any(is.null(xvardef("covariates",object)))) {
return(cat("Covariates are not defined in the current database!\n"))
}
## create enpty list for plots
number.of.plots <- 0
for (i in xvardef("covariates", object)) {
if(!is.factor(object@Data[[i]])){
number.of.plots <- number.of.plots + 1
}
}
plotList <- vector("list",number.of.plots)
plot.num <- 0 # initialize plot number
## loop (ranpar)
for (i in xvardef("covariates", object)) {
if(!is.factor(object@Data[[i]])){
xplot <- xpose.plot.qq(i,
object,
main=NULL,
onlyfirst=onlyfirst,
pass.plot.list=TRUE,
...)
plot.num <- plot.num+1
plotList[[plot.num]] <- xplot
}
}
default.plot.title <- "Distribution of covariates"
plotTitle <- xpose.multiple.plot.title(object=object,
plot.text = default.plot.title,
main=main,
...)
obj <- xpose.multiple.plot(plotList,plotTitle,...)
return(obj)
}
| /scratch/gouwar.j/cran-all/cranData/xpose4/R/cov.qq.R |
#' @describeIn par_cov_splom A scatterplot matrix of covariates
#' @export
cov.splom <- function(object,
main = xpose.multiple.plot.title(object=object,
plot.text = "Scatterplot matrix of covariates",
...),
varnames = NULL,
#xlb = NULL,
#ylb = NULL,
onlyfirst=TRUE,
#inclZeroWRES=FALSE,
#subset=xsubset(object),
smooth = TRUE,
lmline = NULL,
#groups = NULL,
#main.cex=NULL,
...) {
if(any(is.null(xvardef("covariates",object)))) {
return(cat("Covariates are not defined in the current database!\n"))
}
if(is.null(varnames)) {
varnames <- c()
for (i in xvardef("covariates", object)) {
varnames <- c(varnames, xlabel(i, object))
}
}
xplot <- xpose.plot.splom(xvardef("covariates", object),
object,
varnames=varnames,
main = main,
onlyfirst = onlyfirst,
#inclZeroWRES = inclZeroWRES,
#subset = subset,
#groups = groups,
smooth = smooth,
lmline = lmline,
#ylb = ylb,
#xlb = xlb,
...)
return(xplot)
}
| /scratch/gouwar.j/cran-all/cranData/xpose4/R/cov.splom.R |
#' Summarize individual parameter values and covariates
#'
#' These functions produce tables, printed to the screen, summarizing the
#' individual parameter values or covariates from a dataset in Xpose 4.
#'
#'
#' @param object An xpose.data object.
#' @param onlyfirst Logical value indicating if only the first row per
#' individual is included in the plot.
#' @param inclZeroWRES Logical value indicating whether rows with WRES=0 are
#' included in the plot. The default is FALSE.
#' @param out.file Where the results should be output to. Can be ".screen",
#' ".ask", ".graph" or a filename in quotes.
#' @param subset A string giving the subset expression to be applied to the
#' data before plotting. See \code{\link{xsubset}}.
#' @param main The title of the plot. If \code{"Default"} then a default title
#' is plotted. Otherwise the value should be a string like \code{"my title"} or
#' \code{NULL} for no plot title.
#' @param fill The color to fill the boxes in the table if the table is printed
#' to ".graph"
#' @param values.to.use Which values should be summarized
#' @param value.name The name of the values
#' @param max.plots.per.page Maximum plots per page.
#' @param \dots Other arguments passed to \code{Data} and \code{SData}.
#' @return Returned is the matrix of values from the table. \code{parm.summary}
#' and \code{cov.summary} produce summaries of parameters and covariates,
#' respectively. \code{parm.summary} produces less attractive output but
#' supports mirror functionality.
#'
#' \code{parm.summary} and \code{cov.summary} utilize
#' \code{\link[Hmisc]{print.char.matrix}} to print the information to the
#' screen.
#' @author Andrew Hooker & Justin Wilkins
#' @seealso \code{\link{Data}}, \code{\link{SData}},
#' \code{\link{xpose.data-class}}, \code{\link[Hmisc]{print.char.matrix}}
#' @keywords methods
#' @examples
#'
#' parm.summary(simpraz.xpdb)
#'
#' @name par_cov_summary
#' @family data functions
NULL
#' @describeIn par_cov_summary Covariate summary
#' @export
cov.summary <- function(object,
onlyfirst=TRUE,
subset=xsubset(object),
inclZeroWRES=FALSE,
out.file=".screen", # can be ".ask" ".graph" or a file name,
#out.file.sep=",",
main="Default",
fill = "gray",
values.to.use=xvardef("covariates",object),
value.name="Covariate",
...){
return(parm.summary(object,
onlyfirst=onlyfirst,
subset=subset,
out.file=out.file,
main=main,
fill=fill,
values.to.use=values.to.use,
value.name=value.name,
inclZeroWRES=inclZeroWRES,
...) )
}
| /scratch/gouwar.j/cran-all/cranData/xpose4/R/cov.summary.R |
# Xpose 4
# An R-based population pharmacokinetic/
# pharmacodynamic model building aid for NONMEM.
# Copyright (C) 1998-2004 E. Niclas Jonsson and Mats Karlsson.
# Copyright (C) 2005-2008 Andrew C. Hooker, Justin J. Wilkins,
# Mats O. Karlsson and E. Niclas Jonsson.
# Copyright (C) 2009-2010 Andrew C. Hooker, Mats O. Karlsson and
# E. Niclas Jonsson.
# This file is a part of Xpose 4.
# Xpose 4 is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public License
# as published by the Free Software Foundation, either version 3
# of the License, or (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
# You should have received a copy of the GNU Lesser General Public License
# along with this program. A copy can be cound in the R installation
# directory under \share\licenses. If not, see http://www.gnu.org/licenses/.
"covariate.model.menu" <-
function() {
choices <- c("Return to previous menu ->",
"Numerically summarize the covariates",
"Scatterplot matrix of covariates",
"Parameters vs covariates",
"* Parameters vs covariates + model prediction",
"Weighted residuals vs covariates",
"GAM",
"Bootstrap of the GAM", "Bootstrap of the SCM",
"* Tree"
)
title="\nCOVARIATE MODEL MENU\n \\main\\covariate model"
pick <- menu(choices,title=title)
if(is.null(check.vars(c("cwres"),eval(parse(text=".cur.db")),silent=TRUE))) {
wres <- "wres"
}else{
wres <- "cwres"
}
qx <- 0
switch(pick+1,
qx <- 2,
qx <- 1,
cov.summary(eval(parse(text=".cur.db")),out.file=".ask"),
print(cov.splom(eval(parse(text=".cur.db")))),
print(parm.vs.cov(eval(parse(text=".cur.db")))),
cat("\nNot implemented yet!\n"),
##print(wres.vs.cov(eval(parse(text=".cur.db")))),
print(eval(parse(text=paste(wres,".vs.cov(.cur.db)",sep="")))),
qx <- gam.menu(),
qx <- bootgam.menu(),
qx <- bootscm.menu(),
cat("\nNot implemented yet!\n")
)
if(qx == 2) {
return(invisible(2))
} else {
if(qx == 1) {
return(invisible(0))
} else {
Recall()
}
}
}
| /scratch/gouwar.j/cran-all/cranData/xpose4/R/covariate.model.menu.R |
#' Function to create mirror plots from the generic Xpose plotting commands
#'
#' This function takes the generic plotting functions from Xpose 4 and calls
#' them multiple times with the current arguments to the functions, changing
#' the arguments as needed for mirror plotting.
#'
#' mostly and internal function for Xpose
#'
#' @param fun The function name that we will call multiple times
#' @param arg.list The arguments to that function
#' @param mirror The type of mirror plots desired (1 or 3 mirror plots can be
#' created)
#' @param plotTitle The title for the plots
#' @param fix.y.limits Should we fix all the y axes to be the same?
#' @param fix.x.limits Should we fix all the x axes to be the same?
#' @param \dots additional arguments passed to the function.
#' @return a list of plots, or NULL.
#' @author Andrew Hooker
#' @seealso \code{\link{xpose.plot.default}},
#' \code{\link{xpose.plot.histogram}}, \code{\link{xpose.plot.qq}},
#' \code{\link{xpose.plot.splom}}
#' @keywords internal
create.mirror <- function(fun,arg.list,mirror,plotTitle,
fix.y.limits=TRUE,
fix.x.limits=TRUE,
...){
## what sort of mirror do we have?
if(mirror) {
if(!is.logical(mirror)) {
if(mirror != 1 && mirror !=3) {
cat("The mirror should either be logical, 1 or 3!\n")
invisible()
return(NULL)
}
} else {
mirror <- 1
}
}
arg.list$mirror=FALSE
arg.list$...=NULL
if (length(grep("par.strip.text",deparse(match.call())))>0){
par.strip.text.exists <- TRUE
} else {
par.strip.text.exists <- FALSE
}
if (length(grep("auto.key",deparse(match.call())))>0){
auto.key.exists <- TRUE
} else {
auto.key.exists <- FALSE
}
## if strip was not supplied by user and exists then get rid of argument
if(!is.null(arg.list$strip)){
if(!is.null(arg.list$mirror.internal$strip.missing)){
if(arg.list$mirror.internal$strip.missing){
arg.list$strip=NULL
}
}
}
## Set the seed number and decide what simulated data sets to plot
if(!is.null(arg.list$seed)) set.seed(arg.list$seed)
rand.samp <- sample(1:arg.list$object@Nsim,mirror)
## size of labels
if(mirror==3) {
if(is.null(arg.list$y.cex)) arg.list$y.cex=0.6
if(is.null(arg.list$x.cex)) arg.list$x.cex=0.6
}
if(mirror==1) {
arg.list$y.cex=0.8
arg.list$x.cex=0.8
}
if(mirror==1){
if(is.null(arg.list$scales$cex)) arg.list$scales$cex=0.7
if(is.null(arg.list$scales$tck)) arg.list$scales$tck=0.7
#if(is.null(arg.list$scales$cex)) arg.list$scales=list(cex=0.7,tck=0.7)
if(is.null(arg.list$main.cex)) arg.list$main.cex =0.9
if(!par.strip.text.exists) arg.list$par.strip.text$cex =0.9
if(!is.null(arg.list$auto.key)){
if(arg.list$auto.key=="Default") arg.list$auto.key <- list(cex=0.8)
}
}
if(mirror==3){
if(is.null(arg.list$scales$cex)) arg.list$scales$cex=0.5
if(is.null(arg.list$scales$tck)) arg.list$scales$tck=0.5
#if(is.null(arg.list$scales$cex)) arg.list$scales=list(cex=0.5,tck=0.5)
if(is.null(arg.list$main.cex)) arg.list$main.cex =0.7
if(!par.strip.text.exists) arg.list$par.strip.text$cex =0.6
if(!is.null(arg.list$auto.key)){
if(arg.list$auto.key=="Default") arg.list$auto.key <- list(cex=0.6)
}
}
## aspect of graphs
arg.list$aspect=arg.list$mirror.aspect
total.plot.number <- mirror+1
full.plot.list <- vector("list",total.plot.number)
xlb <- arg.list$xlb
for (j in 0:mirror){
## The plot titles
if (j==0) arg.list$main <- "Original data"
if (j!=0) arg.list$main <- paste("Simulated data (#",rand.samp[j],")",sep="")
## The axis labels
arg.list$xlb <- xlb
if (mirror==3 & (j==1 | j==2) ) arg.list$xlb <- " "
if (mirror==1 & j==0) arg.list$xlb <- " "
## the simulation samples
if (j==0) arg.list$samp=NULL
if (j!=0) arg.list$samp=rand.samp[j]
arg.string=NULL
for(argnam in names(arg.list)){
if (is.null(arg.string)){
arg.string="list("
}
arg.string=paste(arg.string,argnam,"=arg.list$",argnam,",",sep="")
}
arg.string=paste(arg.string,"...)",sep="")
evaluated.arg.string <- eval(parse(text=arg.string))
plot.val <- do.call(fun,evaluated.arg.string)
full.plot.list[[j+1]] <- plot.val
}
if(fix.x.limits) xlimits=c()
if(fix.y.limits) ylimits=c()
for (j in 0:mirror){
xplot <- full.plot.list[[j+1]]
if(fix.x.limits) xlimits <- c(xlimits,xplot$x.limits)
if(fix.y.limits) ylimits <- c(ylimits,xplot$y.limits)
}
if(!is.numeric(xlimits)) fix.x.limits <- FALSE
if(!is.numeric(ylimits)) fix.y.limits <- FALSE
if(fix.x.limits) new.xlimits <- c(min(xlimits),max(xlimits))
if(fix.y.limits) new.ylimits <- c(min(ylimits),max(ylimits))
for (j in 0:mirror){
if(fix.x.limits) full.plot.list[[j+1]]$x.limits <- new.xlimits
if(fix.y.limits) full.plot.list[[j+1]]$y.limits <- new.ylimits
}
##if(is.null(arg.list$max.plots.per.page)) arg.list$max.plots.per.page=4
if(arg.list$pass.plot.list){
return(full.plot.list)
} else {
obj <- xpose.multiple.plot(full.plot.list,plotTitle=plotTitle,
#prompt=FALSE,#arg.list$prompt,
#max.plots.per.page=arg.list$max.plots.per.page,
mirror=mirror,
...)
return(obj)
}
}
| /scratch/gouwar.j/cran-all/cranData/xpose4/R/create.mirror.R |
#' @describeIn read_NM_output Reads parameters, uncertainty and termination messages included in a
#' NONMEM output file
#' @export
#'
create.parameter.list <- function(listfile)
{
## Read list file
if(is.readable.file(listfile)) {
x <- read.lst(listfile)
if(length(x)==0 && x == 0) {
cat("The output file does not contain any information")
return()
}
} else {
cat("The output file couldn't be found in the current directory.\n")
return()
}
## Count the number of parameters
npar.list <- calc.npar(x)
#attach(npar.list, warn.conflicts=F)
npar <- npar.list$npar
nth <- npar.list$nth
nseth <- npar.list$nseth
nom <- npar.list$nom
nseom <- npar.list$nseom
nsi <- npar.list$nsi
nsesi <- npar.list$nsesi
seenterm <- seenobj <- seenth <- seenom <- seensi <- seenseth <- seenseom <-
seensesi <- seennth <- seennom <- 0
#attach(x, warn.conflicts=F)
term <- x$term
ofv <- x$ofv
thetas <- x$thetas
omega <- x$omega
sigma <- x$sigma
sethetas <- x$sethetas
seomegas <- x$seomegas
sesigmas <- x$sesigmas
if(!any(is.null(term)))
seenterm <- 1
if(!any(is.null(ofv)))
seenobj <- 1
if(!any(is.null(thetas)))
seenth <- 1
if(!any(is.null(omega)) && nom !=0)
seenom <- 1
if(!any(is.null(sigma)) && nsi !=0)
seensi <- 1
if(!any(is.null(sethetas)))
seenseth <- 1
if(!any(is.null(seomegas)) && nseom !=0)
seenseom <- 1
if(!any(is.null(sesigmas)) && nsesi !=0)
seensesi <-1
## Add parameters
## Construct the parameter information that is to be added to the screen
## This will be in the form of 1 or two arrays, the first being the array
## with parameter estimates and the second with SEs
## The nonparametrics are added to the parameter array afterwards
## The SE array will be constructed wether or not there are SE but filled
## with 0.
## If we haven't got any parameters in the lst-file
if(seenth != 1) {
cat("No parameters found, check your NONMEM output file.\n")
return()
}
## If we have thetas (we should have them!)
if(seenth == 1) {
nth <- length(thetas)
parnam <- 0
parval <- 0
parnam[1:nth] <- paste("TH",1:nth,sep="")
parval[1:nth] <- format.default(thetas,digits=2)
}
## If we have SE for the thetas
if(seenseth == 1) {
nseth <- length(sethetas)
separnam <- 0
separval <- 0
separnam[1:nseth] <- paste("RSE TH",1:nseth,sep="")
## To avoid division by zero or NA
selzero <- thetas == 0
selna <- is.na(sethetas)
sel <- !selzero & !selna
sel1 <- !sel
cvthetas <- 0
cvthetas[sel] <- format.default(sethetas[sel]/abs(thetas[sel]),digits=2)
cvthetas[sel1] <- ""
separval[1:nseth] <- cvthetas
} else {
nth <- length(thetas)
separnam <- 0
separval <- 0
separnam[1:nth] <- paste("RSE TH",1:nth,sep="")
separval[1:nth] <- 0
}
## If we have omegas
if(seenom == 1 ) {
nomega <- length(omega)
for(i in 1:nomega) {
sel <- omega[[i]] != 0
if(nomega == 1) sel <- T
if(i == 1) sel <- T
if(length(omega[[i]][sel]) == 1 || i == 1) { # Must be a diagonal omega
parnam[length(parnam)+1] <- paste("OM",i,":",i,sep="")
## If the first omega is fixed to 0
if(omega[[i]][sel] == 0) {
parval[length(parval)+1] <-
format.default(0,digits=2)
##separnam[length(separnam)+1] <- paste("CT OM",i,":",i,sep="")
separval[length(separval)+1] <- ""
} else {
parval[length(parval)+1] <-
format.default(sqrt(omega[[i]][sel]),digits=2)
separnam[length(separnam)+1] <- paste("CT OM",i,":",i,sep="")
separval[length(separval)+1] <- ""
}
} else { # There are off-diagonals or the whole row is zero
## The diagonal element
parnam[length(parnam)+1] <- paste("OM",i,":",i,sep="")
parval[length(parval)+1] <-
format.default(sqrt(omega[[i]][i]),digits=2)
separnam[length(separnam)+1] <- paste("CT OM",i,":",i,sep="")
separval[length(separval)+1] <- ""
## Loop over the off-diagonals
for(j in 1:(length(omega[[i]])-1)) {
if(omega[[i]][j] == 0) next
if(omega[[i]][j] != 0) {
parnam[length(parnam)+1] <- paste("OM",i,":",j,sep="")
parval[length(parval)+1] <-
format.default(omega[[i]][j]/sqrt(omega[[i]][i]*omega[[j]][j]),digits=2)
separnam[length(separnam)+1] <- paste("CT OM",i,":",j,sep="")
separval[length(separval)+1] <- ""
}
}
}
}
}
## If we have SE for the omegas -- fill in their values
if(seenseom == 1) {
n <- length(thetas) # n - is a flag that makes the values appear
# in the right place
nseomega <- length(seomegas)
for(i in 1:nseomega) {
## Select the non-zero omegas
sel <- omega[[i]] != 0
if(nseomega == 1) sel <- T
if(i == 1) sel <- T
if(length(seomegas[[i]][sel]) == 1) {
## Must be a diagonal omega
n <- n+1
separnam[n] <-
paste("RSE OM",i,":",i,sep="")
if(omega[[i]][sel] == 0) { ## If first omega is fixed to 0
separval[n] <- ""
} else {
if(is.na(seomegas[[i]][sel])){
separval[n] <- ""
} else {
if(seomegas[[i]][sel] == 0){
separval[n] <- ""
} else {
separval[n] <-
format.default(seomegas[[i]][sel]/abs(omega[[i]][sel]),digits=2)
}
}
}
} else {
## There are off-diagonals
n <- n+1
separnam[n] <- paste("RSE OM",i,":",i,sep="")
if(is.na(seomegas[[i]][i])){
separval[n] <- ""
} else {
if(seomegas[[i]][i] == 0){
separval[n] <- ""
} else {
separval[n] <-
format.default(seomegas[[i]][i]/abs(omega[[i]][i]),digits=2)
}
}
## Loop over the off-diagonals
for(j in 1:(length(seomegas[[i]])-1)) {
if(omega[[i]][j] == 0) next
if(omega[[i]][j] != 0) {
n <- n +1
separnam[n] <-
paste("RSE OM",i,":",j,sep="")
if(is.na(seomegas[[i]][j])){
separval[n] <- ""
} else {
if(seomegas[[i]][j] == 0){
separval[n] <- ""
} else {
separval[n] <-
format.default(seomegas[[i]][j]/abs(omega[[i]][j]),digits=2)
}
}
}
}
}
}
}
## capture the length of the parameter vector before sigma added
th.om.par.length <- length(parnam)
## If we have sigmas
if(seensi == 1) {
nsigma <- length(sigma)
for(i in 1:nsigma) {
sel <- sigma[[i]] != 0
if(length(sigma[[i]][sel]) == 1) { # Must be a diagonal omega
parnam[length(parnam)+1] <- paste("SI",i,":",i,sep="")
parval[length(parval)+1] <-
format.default(sqrt(sigma[[i]][sel]),digits=2)
separnam[length(separnam)+1] <- paste("RSE SI",i,":",i,sep="")
separval[length(separval)+1] <- ""
} else { # There are off-diagonals
## The diagonal element
parnam[length(parnam)+1] <- paste("SI",i,":",i,sep="")
parval[length(parval)+1] <-
format.default(sqrt(sigma[[i]][i]),digits=2)
separnam[length(separnam)+1] <- paste("RSE SI",i,":",i,sep="")
separval[length(separval)+1] <- ""
## Loop over the off-diagonals
for(j in 1:(length(sigma[[i]])-1)) {
if(sigma[[i]][j] == 0) next
if(sigma[[i]][j] != 0) {
parnam[length(parnam)+1] <- paste("SI",i,":",j,sep="")
parval[length(parval)+1] <-
format.default(sigma[[i]][j]/sqrt(sigma[[i]][i]*sigma[[j]][j]),digits=2)
separnam[length(separnam)+1] <- paste("RSE SI",i,":",j,sep="")
separval[length(separval)+1] <- ""
}
}
}
}
}
## If we have SE for the sigmas -- fill in their values
if(seensesi == 1) {
n <- th.om.par.length
nsesigma <- length(sesigmas)
for(i in 1:nsesigma) {
sel <- sigma[[i]] != 0
if(nsesigma == 1) sel <- T
if(length(sesigmas[[i]][sel]) == 1) {
## Must be a diagonal omega
n <- n+1
separnam[n]<- paste("RSE SI",i,":",i,sep="")
if(sigma[[i]][sel] == 0) {
## If first sigma is fixed to 0
separval[n]<- ""
} else {
if(is.na(sesigmas[[i]][sel])){
separval[n] <- ""
} else {
if(sesigmas[[i]][sel] == 0){
separval[n] <- ""
} else {
separval[n]<-
format.default(sesigmas[[i]][sel]/abs(sigma[[i]][sel]),digits=2)
}
}
}
} else {
## There are off-diagonals
n <- n+1
separnam[n]<- paste("RSE SI",i,":",i,sep="")
if(is.na(sesigmas[[i]][i])){
separval[n] <- ""
} else {
if(sesigmas[[i]][i] == 0) {
separval[n] <- ""
} else {
separval[n]<-
format.default(sesigmas[[i]][i]/abs(sigma[[i]][i]),digits=2)
}
}
## Loop over the off-diagonals
for(j in 1:(length(sesigmas[[i]])-1)) {
if(sigma[[i]][j] == 0) next
if(sigma[[i]][j] != 0) {
n <- n+1
separnam[n] <-
paste("RSE SI",i,":",j,sep="")
if(is.na(sesigmas[[i]][j])){
separval[n] <- ""
} else {
if(sigma[[i]][j] == 0){
separval[n] <- ""
} else {
separval[n] <-
format.default(sesigmas[[i]][j]/abs(sigma[[i]][j]),digits=2)
}
}
}
}
}
}
}
ret.list <- list(term = term, ofv = ofv,
seenterm = seenterm,
seenobj = seenobj,
seenth = seenth,
seenom = seenom,
seensi = seensi,
seenseth = seenseth,
seenseom = seenseom,
seensesi = seensesi,
npar = npar,
parnam = parnam,
parval = parval,
separnam = separnam,
separval = separval
)
#detach(x)
#detach(npar.list)
return(ret.list)
}
| /scratch/gouwar.j/cran-all/cranData/xpose4/R/create.parameter.list.R |
#' @rdname addid
create.rand <- function(data,object,frac,seed=NULL) {
if(!is.null(seed)) {
set.seed(seed)
} else {
seed <- "noseed"
}
if(missing(frac)) frac <- object@[email protected]$dilfrac
facnam <- paste("R",seed,sep="")
ids <- unique(data[,xvardef("id",object)])
tmp <- data.frame(ID=ids,R=sample(c(0,1),size=length(ids),replace=TRUE,
prob=c(frac,1-frac)))
names(tmp) <- c(xvardef("id",object),facnam)
newdata <- merge(data,tmp,by=xvardef("id",object))
newdata[,facnam] <- as.factor(newdata[,facnam])
xlabel(object) <- c(facnam,facnam)
data[,facnam] <- newdata[,facnam]
names(data)[length(names(data))] <- facnam
invisible()
return(data)
}
| /scratch/gouwar.j/cran-all/cranData/xpose4/R/create.rand.R |
# Xpose 4
# An R-based population pharmacokinetic/
# pharmacodynamic model building aid for NONMEM.
# Copyright (C) 1998-2004 E. Niclas Jonsson and Mats Karlsson.
# Copyright (C) 2005-2008 Andrew C. Hooker, Justin J. Wilkins,
# Mats O. Karlsson and E. Niclas Jonsson.
# Copyright (C) 2009-2010 Andrew C. Hooker, Mats O. Karlsson and
# E. Niclas Jonsson.
# This file is a part of Xpose 4.
# Xpose 4 is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public License
# as published by the Free Software Foundation, either version 3
# of the License, or (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
# You should have received a copy of the GNU Lesser General Public License
# along with this program. A copy can be cound in the R installation
# directory under \share\licenses. If not, see http://www.gnu.org/licenses/.
#' @rdname addid
create.strat.rand <- function(data,object,x,y,frac,dilci,seed=NULL) {
if(!is.null(seed)) {
set.seed(seed)
} else {
seed <- "noseed"
}
if(missing(frac)) frac <- object@[email protected]$dilfrac
if(missing(dilci)) dilci <- object@[email protected]$dilci
facnam <- paste("RS",seed,sep="")
yres <- residuals(loess(formula(paste(y,"~",x)),data))
lims <- quantile(yres,
probs=c(1-dilci,dilci))
## Can sample from the 1s
mp3fun <- function(x,lims) {
ret <- 1
if(any(x < lims[1])) ret <- 0
if(any(x > lims[2])) ret <- 0
ret
}
RR <- tapply(yres,data[,xvardef("id",object)],FUN="mp3fun",lim=lims)
ids <- unique(data[,xvardef("id",object)])
RRR <- sample(c(0,1),size=length(ids),replace=TRUE,
prob=c(frac,1-frac))
tmp <- data.frame(ID=as.factor(names(RR)),
R=RR*RRR)
names(tmp) <- c(xvardef("id",object),facnam)
newdata <- merge(tmp,data,by=xvardef("id",object),sort=FALSE)
newdata[,facnam] <- as.factor(newdata[,facnam])
xlabel(object) <- c(facnam,facnam)
data[,facnam] <- newdata[,facnam]
names(data)[length(names(data))] <- facnam
invisible()
return(data)
}
| /scratch/gouwar.j/cran-all/cranData/xpose4/R/create.strat.rand.R |
# Xpose 4
# An R-based population pharmacokinetic/
# pharmacodynamic model building aid for NONMEM.
# Copyright (C) 1998-2004 E. Niclas Jonsson and Mats Karlsson.
# Copyright (C) 2005-2008 Andrew C. Hooker, Justin J. Wilkins,
# Mats O. Karlsson and E. Niclas Jonsson.
# Copyright (C) 2009-2010 Andrew C. Hooker, Mats O. Karlsson and
# E. Niclas Jonsson.
# This file is a part of Xpose 4.
# Xpose 4 is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public License
# as published by the Free Software Foundation, either version 3
# of the License, or (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
# You should have received a copy of the GNU Lesser General Public License
# along with this program. A copy can be cound in the R installation
# directory under \share\licenses. If not, see http://www.gnu.org/licenses/.
#' Create xpose.multiple.plot class.
#'
#' Creates a class for viewing and plotting xpose plots with multiple plots on
#' the same page or multiple pages.
#'
#'
#' @aliases create.xpose.plot.classes print,xpose.multiple.plot-method
#' @author Niclas Jonsson and Andrew C. Hooker
#' @export
create.xpose.plot.classes <- function()
{
setClassUnion("character or NULL",c("character","NULL"))
setClassUnion("character or numeric",c("character","numeric"))
setClassUnion("numeric or NULL",c("numeric","NULL"))
setClassUnion("data.frame or NULL",c("data.frame","NULL"))
setClassUnion("list or NULL",c("list","NULL"))
setClassUnion("lang or numeric",c("vector","numeric","list"))
setClassUnion("logical or numeric",c("logical","numeric"))
setClass("xpose.multiple.plot",#where=.GlobalEnv,
representation(plotList = "list or NULL",
plotTitle = "character or NULL",
prompt = "logical",
new.first.window = "logical",
max.plots.per.page = "numeric",
title = "list",
##title.x = "xptmp",
##title.y = "lang or numeric",
##title.just = "vector",
##title.gp = "lang or numeric",
mirror = "logical or numeric",
bql.layout = "logical"
),
prototype(plotList = NULL,
plotTitle= NULL,
prompt = FALSE,
new.first.window = FALSE,
max.plots.per.page = 4,
title = list(
title.x = unit(0.5, "npc"),
title.y = unit(0.5, "npc"),
title.gp= gpar(cex=1.2,fontface="bold"),#,font=2),
title.just = c("center","center")
),
##title.x = unit(0.5, "npc"),
##title.y = c(unit(0.5, "npc")),
##title.just = c("center","center"),
##title.gp = list(cex=1.2,fontface="bold",font=2),
mirror = FALSE,
bql.layout = FALSE
)
)
## Define the methods
setMethod("print",signature(x="xpose.multiple.plot"),print.xpose.multiple.plot)
setMethod("show","xpose.multiple.plot",function(object) print(x=object))
invisible()
}
| /scratch/gouwar.j/cran-all/cranData/xpose4/R/create.xpose.plot.classes.R |
#' This function creates the Xpose data classes ("xpose.data" and
#' "xpose.prefs")
#'
#' This function defines and sets the Xpose data classes.
#'
#'
#' @param nm7 \code{FALSE} if not using NONMEM 7.
#' @note All the default settings are defined in this function.
#' @author Niclas Jonsson and Andrew C. Hooker
#' @seealso \code{\link{xpose.data-class}},\code{\link{xpose.prefs-class}}
#' @keywords methods
#' @export createXposeClasses
"createXposeClasses" <-
function(nm7=F) {
setClassUnion("character or NULL",c("character","NULL"),where=.GlobalEnv)
setClassUnion("character or numeric",c("character","numeric"),where=.GlobalEnv)
setClassUnion("numeric or NULL",c("numeric","NULL"),where=.GlobalEnv)
setClassUnion("data.frame or NULL",c("data.frame","NULL"),where=.GlobalEnv)
setClassUnion("list or NULL",c("list","NULL"),where=.GlobalEnv)
setClassUnion("lang or numeric",c("vector","numeric","list"),where=.GlobalEnv)
setClassUnion("logical or numeric",c("logical","numeric"),where=.GlobalEnv)
if(nm7) ipred.def <- "IPRED" else ipred.def <- "IPRE"
if(nm7) iwres.def <- "IWRES" else iwres.def <- "IWRE"
if(nm7) {
labels.list = list(
OCC = "Occasion",
TIME = "Time",
PRED = "Population predictions",
IPRED = "Individual predictions",
WRES = "Weighted residuals",
CWRES = "Conditional weighted residuals",
IWRES = "Individual weighted residuals",
DV = "Observations",
RES = "Residuals",
CL = "Clearance",
V = "Volume",
TAD = "Time after dose"
)
} else {
labels.list = list(
OCC = "Occasion",
TIME = "Time",
PRED = "Population predictions",
IPRE = "Individual predictions",
WRES = "Weighted residuals",
CWRES = "Conditional weighted residuals",
IWRE = "Individual weighted residuals",
DV = "Observations",
RES = "Residuals",
CL = "Clearance",
V = "Volume",
TAD = "Time after dose"
)
}
setClass("xpose.prefs",where=.GlobalEnv,
#representation =
slots = c(Xvardef = "list",
Labels = "list",
Graph.prefs = "list",
Miss = "numeric",
Cat.levels = "numeric",
DV.Cat.levels = "numeric",
Subset = "character or NULL",
Gam.prefs = "list",
Bootgam.prefs = "list"
),
prototype=list(
Xvardef = list(
id = "ID",
idlab = "ID",
idv = "TIME",
occ = "OCC",
dv = "DV",
pred = "PRED",
ipred = ipred.def,
iwres = iwres.def,
wres = "WRES",
cwres = "CWRES",
res = "RES",
parms = c("CL","V","V1","V2","V3","Q","Q1","Q2","Q3","KA",
"ETA1","ETA2","ETA3","ETA4","ETA5","ETA6","ETA7",
"ETA8","ETA9","ET10","ET11","ET12","ET13","ET14",
"ET15","ET16","ET17","ET18","ET19","ET20"),
covariates = c("GENO","SEX","RACE","DOSE","FLAG","DAY","PAT",
"GEND","AGE","WT","HT","CRCL","CLCR"),
ranpar = c("ETA1","ETA2","ETA3","ETA4","ETA5","ETA6","ETA7",
"ETA8","ETA9","ET10","ET11","ET12","ET13","ET14","ET15",
"ET16","ET17","ET18","ET19","ET20"),
tvparms = c("TVCL","TVV","TVV1","TVV2","TVV3","TVQ","TVQ1",
"TVQ2","TVQ3","TVKA")
),
Labels = labels.list,
Graph.prefs = list(
type = "b" ,
pch = 1 ,
cex = 0.8 ,
lty = 1 ,
lwd = 1 ,
col = 4 ,
fill = "lightblue",
grid = FALSE ,
aspect = "fill" ,
## By arguments
condvar = NULL,
byordfun = "median" ,
ordby = NULL ,
shingnum = 6 ,
shingol = 0.5 ,
## Abline settings
abline = NULL ,
abllwd = 1 ,
ablcol = 1 ,
abllty = 1,
## Smooth settings
smooth = NULL ,
smlwd = 2 ,
smcol = "red" ,
smlty = 1 ,
smspan = 2/3 ,
smdegr = 1,
## Lm settings
lmline = NULL,
lmlwd = 2,
lmcol = 2,
lmlty = 1,
## Superpose line settings
suline = NULL,
sulwd = 2,
sucol = 3,
sulty = 1,
suspan = 2/3,
sudegr = 1,
## Text label settings,
ids = FALSE,
idsmode= NULL,
idsext = 0.05, ## In each end
idscex = 0.7,
idsdir = "both",
## Dilution stuff
dilfrac = 0.7,
diltype = NULL,
dilci = 0.95,
## Prediction interval stuff
PIuplty = 2,
PIdolty = 2,
PImelty = 1,
PIuptyp = "l",
PIdotyp = "l",
PImetyp = "l",
PIupcol = "black",
PIdocol = "black",
PImecol = "black",
PIuplwd = 2,
PIdolwd = 2,
PImelwd = 2,
PIupltyR = 1,
PIdoltyR = 1,
PImeltyR = 2,
PIuptypR = "l",
PIdotypR = "l",
PImetypR = "l",
PIupcolR = "blue",
PIdocolR = "blue",
PImecolR = "blue",
PIuplwdR = 2,
PIdolwdR = 2,
PImelwdR = 2,
PIupltyM = 1,
PIdoltyM = 1,
PImeltyM = 2,
PIuptypM = "l",
PIdotypM = "l",
PImetypM = "l",
PIupcolM = "darkgreen",
PIdocolM = "darkgreen",
PImecolM = "darkgreen",
PIuplwdM = 0.5,
PIdolwdM = 0.5,
PImelwdM = 0.5,
PIarcol = "lightgreen",
PIlimits=c(0.025,0.975),
## Categorical x-variable
bwhoriz = FALSE,
bwratio = 1.5,
bwvarwid = FALSE,
bwdotpch = 16,
bwdotcol = "black",
bwdotcex = 1,
bwreccol = "blue",
bwrecfill= "transparent",
bwreclty = 1,
bwreclwd = 1,
bwumbcol = "blue",
bwumblty = 1,
bwumblwd = 1,
bwoutcol ="blue" ,
bwoutcex = 0.8,
bwoutpch = 1,
##Histogram settings
hicol = 5,#"blue",
hiborder = "black",
hilty = 1,
hilwd = 1,
hidlty = 2,
hidlwd = 2,
hidcol = 1
),
Miss = -99,
Cat.levels = 4,
DV.Cat.levels = 7,
Subset = NULL,
Gam.prefs = list(
onlyfirst=TRUE,
wts=FALSE,
start.mod=NULL,
steppit=TRUE,
disp = NULL,
nmods=3,
smoother1=0,
smoother2=1,
smoother3="ns",
smoother4="ns",
arg1=NULL,
arg2=NULL,
arg3="df=2",
arg4="df=3",
excl1=NULL,
excl2=NULL,
excl3=NULL,
excl4=NULL,
extra=NULL,
plot.ids=TRUE,
medianNorm=TRUE
),
Bootgam.prefs = list(n = 100,
algo = "fluct.ratio",
conv.value = as.numeric(1.04),
check.interval = as.numeric(20),
start.check = as.numeric(50),
liif = as.numeric(0.2),
ljif.conv = as.numeric(25),
seed = NULL,
start.mod = NULL,
excluded.ids = NULL
)
)
)
setClass("xpose.data",where=.GlobalEnv,
slots=c(Data = "data.frame or NULL",
SData = "data.frame or NULL",
Data.firstonly = "data.frame or NULL",
SData.firstonly = "data.frame or NULL",
Runno = "character or numeric",
Nsim = "numeric or NULL",
Doc = "character or NULL",
Prefs = "xpose.prefs"
),
prototype=list(Data = NULL,
SData = NULL,
Data.firstonly = NULL,
SData.firstonly = NULL,
Nsim = NULL,
Runno = NULL,
Doc = NULL),
validity = test.xpose.data
)
invisible()
}
| /scratch/gouwar.j/cran-all/cranData/xpose4/R/createXposeClasses.R |
# Xpose 4
# An R-based population pharmacokinetic/
# pharmacodynamic model building aid for NONMEM.
# Copyright (C) 1998-2004 E. Niclas Jonsson and Mats Karlsson.
# Copyright (C) 2005-2008 Andrew C. Hooker, Justin J. Wilkins,
# Mats O. Karlsson and E. Niclas Jonsson.
# Copyright (C) 2009-2010 Andrew C. Hooker, Mats O. Karlsson and
# E. Niclas Jonsson.
# This file is a part of Xpose 4.
# Xpose 4 is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public License
# as published by the Free Software Foundation, either version 3
# of the License, or (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
# You should have received a copy of the GNU Lesser General Public License
# along with this program. A copy can be cound in the R installation
# directory under \share\licenses. If not, see http://www.gnu.org/licenses/.
#' Histogram of conditional weighted residuals (CWRES), for Xpose 4
#'
#' This is a histogram of the distribution of conditional weighted residuals
#' (CWRES) in the dataset, a specific function in Xpose 4. It is a wrapper
#' encapsulating arguments to the \code{xpose.plot.histogram} function.
#'
#' Displays a histogram of the conditional weighted residuals (CWRES).
#'
#' @param object An xpose.data object.
#' @param \dots Other arguments passed to \code{\link{xpose.plot.histogram}}.
#' @return Returns a histogram of conditional weighted residuals (CWRES).
#' @author E. Niclas Jonsson, Mats Karlsson, Andrew Hooker & Justin Wilkins
#' @seealso \code{\link{xpose.plot.histogram}},
#' \code{\link{xpose.panel.histogram}}, \code{\link[lattice]{histogram}},
#' \code{\link{xpose.prefs-class}}, \code{\link{compute.cwres}},
#' \code{\link{xpose.data-class}}
#' @keywords methods
#' @examples
#' ## Here we load the example xpose database
#' xpdb <- simpraz.xpdb
#'
#' ## A vanilla plot
#' cwres.dist.hist(xpdb)
#'
#' @export
#' @family specific functions
"cwres.dist.hist" <-
function(object,
...) {
if(is.null(check.vars(c("cwres"),
object,silent=FALSE))) {
return()
}
xplot <- xpose.plot.histogram(xvardef("cwres",object),
object,
...)
return(xplot)
}
| /scratch/gouwar.j/cran-all/cranData/xpose4/R/cwres.dist.hist.R |
# Xpose 4
# An R-based population pharmacokinetic/
# pharmacodynamic model building aid for NONMEM.
# Copyright (C) 1998-2004 E. Niclas Jonsson and Mats Karlsson.
# Copyright (C) 2005-2008 Andrew C. Hooker, Justin J. Wilkins,
# Mats O. Karlsson and E. Niclas Jonsson.
# Copyright (C) 2009-2010 Andrew C. Hooker, Mats O. Karlsson and
# E. Niclas Jonsson.
# This file is a part of Xpose 4.
# Xpose 4 is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public License
# as published by the Free Software Foundation, either version 3
# of the License, or (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
# You should have received a copy of the GNU Lesser General Public License
# along with this program. A copy can be cound in the R installation
# directory under \share\licenses. If not, see http://www.gnu.org/licenses/.
## Added by Justin Wilkins
## 28/11/2005
#' Quantile-quantile plot of conditional weighted residuals (CWRES), for Xpose
#' 4
#'
#' This is a QQ plot of the distribution of conditional weighted residuals
#' (CWRES) in the dataset, a specific function in Xpose 4. It is a wrapper
#' encapsulating arguments to the \code{xpose.plot.qq} function.
#'
#' Displays a QQ plot of the conditional weighted residuals (CWRES).
#'
#' @param object An xpose.data object.
#' @param \dots Other arguments passed to \code{link{xpose.plot.qq}}.
#' @return Returns a QQ plot of conditional weighted residuals (CWRES).
#' @author E. Niclas Jonsson, Mats Karlsson, Andrew Hooker & Justin Wilkins
#' @seealso \code{\link{xpose.plot.qq}}, \code{\link{xpose.panel.qq}},
#' \code{\link[lattice]{qqmath}}, \code{\link{xpose.prefs-class}},
#' \code{\link{compute.cwres}}, \code{\link{xpose.data-class}}
#' @keywords methods
#' @examples
#'
#' cwres.dist.qq(simpraz.xpdb)
#'
#' @export cwres.dist.qq
#' @family specific functions
cwres.dist.qq <-
function(object,
#main = NULL,
#xlb = NULL,
#ylb = NULL,
#onlyfirst=FALSE,
#inclZeroWRES=FALSE,
#subset=xsubset(object),
#mirror=FALSE,
#seed = NULL,
#samp = NULL,
#pch=object@[email protected]$pch,
#col=object@[email protected]$col,
#abllty = object@[email protected]$abllty,
#abllwd = object@[email protected]$abllwd,
#ablcol = object@[email protected]$ablcol,
...) {
if(is.null(xvardef("cwres",object))) {
cat("CWRES is not set in the database!\n")
return()
}
xplot <- xpose.plot.qq(xvardef("cwres",object),
#xlb = xlb,
# ylb = ylb,
object,
# main=list(main),
# scales=list(cex=0.7,tck=0.5),
# aspect="fill",
#xvar = xvardef("cwres",object),
#pch=pch,
#col=col,
#abllty=abllty,
#abllwd=abllwd,
#ablcol=ablcol,
#subset=subset,
...)
return(xplot)
}
| /scratch/gouwar.j/cran-all/cranData/xpose4/R/cwres.dist.qq.R |
# Xpose 4
# An R-based population pharmacokinetic/
# pharmacodynamic model building aid for NONMEM.
# Copyright (C) 1998-2004 E. Niclas Jonsson and Mats Karlsson.
# Copyright (C) 2005-2008 Andrew C. Hooker, Justin J. Wilkins,
# Mats O. Karlsson and E. Niclas Jonsson.
# Copyright (C) 2009-2010 Andrew C. Hooker, Mats O. Karlsson and
# E. Niclas Jonsson.
# This file is a part of Xpose 4.
# Xpose 4 is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public License
# as published by the Free Software Foundation, either version 3
# of the License, or (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
# You should have received a copy of the GNU Lesser General Public License
# along with this program. A copy can be cound in the R installation
# directory under \share\licenses. If not, see http://www.gnu.org/licenses/.
"cwres.menu" <- function() {
choices <- c("Return to previous menu ->",
"Compute CWRES",
"Compare CWRES and weighted residuals",
"Basic goodness of fit plots using CWRES",
"CWRES vs independent variable",
"CWRES vs independent variable (BW)",
"CWRES vs PRED",
"CWRES vs PRED (BW)",
"Distribution of CWRES (hist)",
"Distribution of CWRES (QQ)",
"Individual distributions of CWRES (hist)",
"Individual distributions of CWRES (QQ)",
"Absolute value of CWRES vs predictions",
"Covariates vs absolute value of CWRES (BW)",
"Absolute value of CWRES vs pred|covariates",
"Autocorrelation of CWRES"
)
title="\nCONDITIONAL WEIGHTED RESIDUALS (CWRES) MENU\n \\main\\Conditional weighted residuals"
pick <- menu(choices,title=title)
qx <- 0
switch(pick+1,
qx <- 2,
qx <- 1,
xpose.calculate.cwres(eval(parse(text=".cur.db")),classic=TRUE),
print(cwres.wres.vs.idv(eval(parse(text=".cur.db")))),
print(basic.gof(eval(parse(text=".cur.db")))),
print(cwres.vs.idv(eval(parse(text=".cur.db")))),
print(cwres.vs.idv.bw(eval(parse(text=".cur.db")))),
print(cwres.vs.pred(eval(parse(text=".cur.db")))),
print(cwres.vs.pred.bw(eval(parse(text=".cur.db")))),
print(cwres.dist.hist(eval(parse(text=".cur.db")))),
print(cwres.dist.qq(eval(parse(text=".cur.db")))),
print(ind.plots.cwres.hist(eval(parse(text=".cur.db")))),
print(ind.plots.cwres.qq(eval(parse(text=".cur.db")))),
print(absval.cwres.vs.pred(eval(parse(text=".cur.db")))),
print(absval.cwres.vs.cov.bw(eval(parse(text=".cur.db")),bins=9)),
print(absval.cwres.vs.pred.by.cov(eval(parse(text=".cur.db")))),
print(autocorr.cwres(eval(parse(text=".cur.db"))))
)
if(qx == 2) {
return(invisible(2))
} else {
if(qx == 1) {
return(invisible(0))
} else {
Recall()
}
}
}
| /scratch/gouwar.j/cran-all/cranData/xpose4/R/cwres.menu.R |
# Xpose 4
# An R-based population pharmacokinetic/
# pharmacodynamic model building aid for NONMEM.
# Copyright (C) 1998-2004 E. Niclas Jonsson and Mats Karlsson.
# Copyright (C) 2005-2008 Andrew C. Hooker, Justin J. Wilkins,
# Mats O. Karlsson and E. Niclas Jonsson.
# Copyright (C) 2009-2010 Andrew C. Hooker, Mats O. Karlsson and
# E. Niclas Jonsson.
# This file is a part of Xpose 4.
# Xpose 4 is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public License
# as published by the Free Software Foundation, either version 3
# of the License, or (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
# You should have received a copy of the GNU Lesser General Public License
# along with this program. A copy can be cound in the R installation
# directory under \share\licenses. If not, see http://www.gnu.org/licenses/.
#' Conditional Weighted residuals (CWRES) plotted against covariates, for Xpose
#' 4
#'
#' This creates a stack of plots of conditional weighted residuals (CWRES)
#' plotted against covariates, and is a specific function in Xpose 4. It is a
#' wrapper encapsulating arguments to the \code{xpose.plot.default} and
#' \code{xpose.plot.histogram} functions. Most of the options take their
#' default values from xpose.data object but may be overridden by supplying
#' them as arguments.
#'
#' Each of the covariates in the Xpose data object, as specified in
#' \code{object@Prefs@Xvardef$Covariates}, is evaluated in turn, creating a
#' stack of plots.
#'
#' Conditional weighted residuals (CWRES) require some extra steps to
#' calculate. See \code{\link{compute.cwres}} for details.
#'
#' A wide array of extra options controlling xyplots and histograms are
#' available. See \code{\link{xpose.plot.default}} and
#' \code{\link{xpose.plot.histogram}} for details.
#'
#' @param object An xpose.data object.
#' @param ylb A string giving the label for the y-axis. \code{NULL} if none.
#' @param smooth A \code{NULL} value indicates that no superposed line should
#' be added to the graph. If \code{TRUE} then a smooth of the data will be
#' superimposed.
#' @param type 1-character string giving the type of plot desired. The
#' following values are possible, for details, see 'plot': '"p"' for points,
#' '"l"' for lines, '"o"' for over-plotted points and lines, '"b"', '"c"') for
#' (empty if '"c"') points joined by lines, '"s"' and '"S"' for stair steps and
#' '"h"' for histogram-like vertical lines. Finally, '"n"' does not produce
#' any points or lines.
#' @param main The title of the plot. If \code{"Default"} then a default title
#' is plotted. Otherwise the value should be a string like \code{"my title"} or
#' \code{NULL} for no plot title.
#' @param \dots Other arguments passed to \code{link{xpose.plot.default}} or
#' \code{link{xpose.plot.histogram}}.
#' @return Returns a stack of xyplots and histograms of CWRES versus
#' covariates.
#' @author E. Niclas Jonsson, Mats Karlsson, Andrew Hooker & Justin Wilkins
#' @seealso \code{\link{xpose.plot.default}},
#' \code{\link{xpose.plot.histogram}}, \code{\link[lattice]{xyplot}},
#' \code{\link[lattice]{histogram}}, \code{\link{xpose.prefs-class}},
#' \code{\link{compute.cwres}}, \code{\link{xpose.data-class}}
#' @keywords methods
#' @examples
#' ## Here we load the example xpose database
#' xpdb <- simpraz.xpdb
#'
#' cwres.vs.cov(xpdb)
#'
#' @export cwres.vs.cov
#' @family specific functions
cwres.vs.cov <-
function(object,
#xlb = NULL,
ylb = "CWRES",
#onlyfirst=FALSE,
#inclZeroWRES=FALSE,
#subset=xsubset(object),
# abline=c(0,1),
smooth=TRUE,
#abllwd=2,
type="p",
#mirror=FALSE,
#seed = NULL,
#prompt = TRUE,
main="Default",
...) {
## check for arguments in function
if(is.null(check.vars(c("covariates","cwres"),
object,silent=FALSE))) {
return()
}
## create list for plots
number.of.plots <- 0
for (i in xvardef("covariates", object)) {
number.of.plots <- number.of.plots + 1
}
plotList <- vector("list",number.of.plots)
plot.num <- 0 # initialize plot number
## loop (covs)
for (j in xvardef("covariates", object)) {
xplot <- xpose.plot.default(j,
xvardef("cwres",object),
object,
main=NULL,
#xlb = xlb,
ylb = ylb,
#abline=abline,
#abllwd=abllwd,
smooth=smooth,
type=type,
#subset=subset,
pass.plot.list=TRUE,
...)
plot.num <- plot.num+1
plotList[[plot.num]] <- xplot
}
default.plot.title <- paste(xlabel(xvardef("cwres",object),object),
" vs ",
"Covariates",
sep="")
plotTitle <- xpose.multiple.plot.title(object=object,
plot.text = default.plot.title,
main=main,
...)
obj <- xpose.multiple.plot(plotList,plotTitle,...)
return(obj)
}
| /scratch/gouwar.j/cran-all/cranData/xpose4/R/cwres.vs.cov.R |
# Xpose 4
# An R-based population pharmacokinetic/
# pharmacodynamic model building aid for NONMEM.
# Copyright (C) 1998-2004 E. Niclas Jonsson and Mats Karlsson.
# Copyright (C) 2005-2008 Andrew C. Hooker, Justin J. Wilkins,
# Mats O. Karlsson and E. Niclas Jonsson.
# Copyright (C) 2009-2010 Andrew C. Hooker, Mats O. Karlsson and
# E. Niclas Jonsson.
# This file is a part of Xpose 4.
# Xpose 4 is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public License
# as published by the Free Software Foundation, either version 3
# of the License, or (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
# You should have received a copy of the GNU Lesser General Public License
# along with this program. A copy can be cound in the R installation
# directory under \share\licenses. If not, see http://www.gnu.org/licenses/.
#' Population conditional weighted residuals (CWRES) plotted against the
#' independent variable (IDV) for Xpose 4
#'
#' This is a plot of population conditional weighted residuals (CWRES) vs the
#' independent variable (IDV), a specific function in Xpose 4. It is a wrapper
#' encapsulating arguments to the \code{xpose.plot.default} function. Most of
#' the options take their default values from xpose.data object but may be
#' overridden by supplying them as arguments.
#'
#' Conditional weighted residuals (CWRES) are plotted against the independent
#' variable, as specified in \code{object@Prefs@Xvardef$idv}.
#'
#' Conditional weighted residuals (CWRES) require some extra steps to
#' calculate. See \code{\link{compute.cwres}} for details.
#'
#' A wide array of extra options controlling xyplots are available. See
#' \code{\link{xpose.plot.default}} and \code{\link{xpose.panel.default}} for
#' details.
#'
#' @param object An xpose.data object.
#' @param abline Vector of arguments to the \code{\link[lattice]{panel.abline}}
#' function. No abline is drawn if \code{NULL}.
#' @param smooth A \code{NULL} value indicates that no superposed line should
#' be added to the graph. If \code{TRUE} then a smooth of the data will be
#' superimposed.
#' @param \dots Other arguments passed to \code{link{xpose.plot.default}}.
#' @return Returns an xyplot of CWRES vs IDV.
#' @author E. Niclas Jonsson, Mats Karlsson, Andrew Hooker & Justin Wilkins
#' @seealso \code{\link{xpose.plot.default}},
#' \code{\link{xpose.panel.default}}, \code{\link[lattice]{xyplot}},
#' \code{\link{xpose.prefs-class}}, \code{\link{compute.cwres}},
#' \code{\link{xpose.data-class}}
#' @keywords methods
#' @examples
#' ## Here we load the example xpose database
#' xpdb <- simpraz.xpdb
#'
#' ## A vanilla plot
#' cwres.vs.idv(xpdb)
#'
#' ## A conditioning plot
#' cwres.vs.idv(xpdb, by="HCTZ")
#'
#' @export cwres.vs.idv
#' @family specific functions
cwres.vs.idv <-
function(object,
abline=c(0,0),
smooth=TRUE,
...) {
if(is.null(check.vars(c("idv","cwres"),
object,silent=FALSE))) {
return()
}
xplot <- xpose.plot.default(xvardef("idv",object),
xvardef("cwres",object),
smooth = smooth,
abline=abline,
object,
...)
return(xplot)
}
| /scratch/gouwar.j/cran-all/cranData/xpose4/R/cwres.vs.idv.R |
# Xpose 4
# An R-based population pharmacokinetic/
# pharmacodynamic model building aid for NONMEM.
# Copyright (C) 1998-2004 E. Niclas Jonsson and Mats Karlsson.
# Copyright (C) 2005-2008 Andrew C. Hooker, Justin J. Wilkins,
# Mats O. Karlsson and E. Niclas Jonsson.
# Copyright (C) 2009-2010 Andrew C. Hooker, Mats O. Karlsson and
# E. Niclas Jonsson.
# This file is a part of Xpose 4.
# Xpose 4 is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public License
# as published by the Free Software Foundation, either version 3
# of the License, or (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
# You should have received a copy of the GNU Lesser General Public License
# along with this program. A copy can be cound in the R installation
# directory under \share\licenses. If not, see http://www.gnu.org/licenses/.
## Added by Justin Wilkins
## 20/10/2005
#' Box-and-whisker plot of conditional weighted residuals vs the independent
#' variable for Xpose 4
#'
#' This creates a box and whisker plot of conditional weighted residuals
#' (CWRES) vs the independent variable (IDV), and is a specific function in
#' Xpose 4. It is a wrapper encapsulating arguments to the
#' \code{xpose.plot.bw} function. Most of the options take their default values
#' from xpose.data object but may be overridden by supplying them as arguments.
#'
#'
#' This creates a box and whisker plot of conditional weighted residuals
#' (CWRES) vs the independent variable (IDV), and is a specific function in
#' Xpose 4. It is a wrapper encapsulating arguments to the
#' \code{\link{xpose.plot.bw}} function. Most of the options take their default
#' values from xpose.data object but may be overridden by supplying them as
#' arguments.
#'
#' Conditional weighted residuals (CWRES) require some extra steps to
#' calculate. See \code{\link{compute.cwres}} for details.
#'
#' A wide array of extra options controlling bwplots are available. See
#' \code{\link{xpose.plot.bw}} and \code{\link{xpose.panel.bw}} for details.
#'
#' @param object An xpose.data object.
#' @param \dots Other arguments passed to \code{link{xpose.plot.bw}}.
#' @return Returns a stack of box-and-whisker plots of CWRES vs IDV.
#' @author E. Niclas Jonsson, Mats Karlsson, Andrew Hooker & Justin Wilkins
#' @seealso \code{\link{xpose.plot.bw}}, \code{\link{xpose.panel.bw}},
#' \code{\link[lattice]{bwplot}}, \code{\link{xpose.prefs-class}},
#' \code{\link{compute.cwres}}, \code{\link{xpose.data-class}}
#' @keywords methods
#' @examples
#' ## Here we load the example xpose database
#' xpdb <- simpraz.xpdb
#'
#' cwres.vs.idv.bw(xpdb)
#'
#' @export
#' @family specific functions
cwres.vs.idv.bw <-
function(object,
#main = NULL,
#xlb = NULL,
#ylb = NULL,
#onlyfirst=FALSE,
#inclZeroWRES=FALSE,
#subset=xsubset(object),
#mirror=FALSE,
#seed = NULL,
#bins = 10,
#samp = NULL,
...) {
## check for arguments in function
if(is.null(check.vars(c("cwres","idv"),
object,silent=FALSE))) {
return()
}
xplot <- xpose.plot.bw(xvardef("cwres",object),
xvardef("idv",object),
#xlb = xlb,
#ylb = ylb,
#scales=list(cex=0.5,tck=0.5),
#aspect="fill",
object,#main=list(main,cex=0.7),
#main = main,
#bins=bins,
#ids=FALSE,
binvar = xvardef("idv",object),
#xvar = xvardef("cwres",object),
#subset=subset,
...)
return(xplot)
}
| /scratch/gouwar.j/cran-all/cranData/xpose4/R/cwres.vs.idv.bw.R |
# Xpose 4
# An R-based population pharmacokinetic/
# pharmacodynamic model building aid for NONMEM.
# Copyright (C) 1998-2004 E. Niclas Jonsson and Mats Karlsson.
# Copyright (C) 2005-2008 Andrew C. Hooker, Justin J. Wilkins,
# Mats O. Karlsson and E. Niclas Jonsson.
# Copyright (C) 2009-2010 Andrew C. Hooker, Mats O. Karlsson and
# E. Niclas Jonsson.
# This file is a part of Xpose 4.
# Xpose 4 is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public License
# as published by the Free Software Foundation, either version 3
# of the License, or (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
# You should have received a copy of the GNU Lesser General Public License
# along with this program. A copy can be cound in the R installation
# directory under \share\licenses. If not, see http://www.gnu.org/licenses/.
#' Population conditional weighted residuals (CWRES) plotted against population
#' predictions (PRED) for Xpose 4
#'
#' This is a plot of population conditional weighted residuals (cwres) vs
#' population predictions (PRED), a specific function in Xpose 4. It is a
#' wrapper encapsulating arguments to the \code{xpose.plot.default} function.
#' Most of the options take their default values from xpose.data object but may
#' be overridden by supplying them as arguments.
#'
#'
#' Conditional weighted residuals (CWRES) require some extra steps to
#' calculate. See \code{\link{compute.cwres}} for details.
#'
#' A wide array of extra options controlling xyplots are available. See
#' \code{\link{xpose.plot.default}} and \code{\link{xpose.panel.default}} for
#' details.
#'
#' @param object An xpose.data object.
#' @param smooth Logical value indicating whether an x-y smooth should be
#' superimposed. The default is TRUE.
#' @param abline Vector of arguments to the \code{\link[lattice]{panel.abline}}
#' function. No abline is drawn if \code{NULL}.
#' @param \dots Other arguments passed to \code{link{xpose.plot.default}}.
#' @return Returns an xyplot of CWRES vs PRED.
#' @author E. Niclas Jonsson, Mats Karlsson, Andrew Hooker & Justin Wilkins
#' @seealso \code{\link{xpose.plot.default}}, \code{\link[lattice]{xyplot}},
#' \code{\link{xpose.prefs-class}}, \code{\link{compute.cwres}},
#' \code{\link{xpose.data-class}}
#' @keywords methods
#' @examples
#' ## Here we load the example xpose database
#' xpdb <- simpraz.xpdb
#'
#' cwres.vs.pred(xpdb)
#'
#' ## A conditioning plot
#' cwres.vs.pred(xpdb, by="HCTZ")
#'
#' @export cwres.vs.pred
#' @family specific functions
cwres.vs.pred <-
function(object,
abline=c(0,0),
#main = NULL,
#xlb = NULL,
#ylb = NULL,
#onlyfirst=FALSE,
#inclZeroWRES=FALSE,
#subset=xsubset(object),
#mirror=FALSE,
#seed = NULL,
smooth = TRUE,
...) {
## check for arguments in function
if(is.null(check.vars(c("cwres","pred"),
object,silent=FALSE))) {
return()
}
xplot <- xpose.plot.default(xvardef("pred",object),
xvardef("cwres",object),
object,#main=main,
#xlb = xlb,
#ylb=ylb,
smooth = smooth,
abline=abline,#subset=subset,
...)
return(xplot)
}
| /scratch/gouwar.j/cran-all/cranData/xpose4/R/cwres.vs.pred.R |
#' Box-and-whisker plot of conditional weighted residuals vs population
#' predictions for Xpose 4
#'
#' This creates a box and whisker plot of conditional weighted residuals
#' (CWRES) vs population predictions (PRED), and is a specific function in
#' Xpose 4. It is a wrapper encapsulating arguments to the
#' \code{xpose.plot.bw} function. Most of the options take their default values
#' from xpose.data object but may be overridden by supplying them as arguments.
#'
#'
#' This creates a box and whisker plot of conditional weighted residuals
#' (CWRES) vs population predictions (PRED), and is a specific function in
#' Xpose 4. It is a wrapper encapsulating arguments to the
#' \code{xpose.plot.bw} function. Most of the options take their default values
#' from xpose.data object but may be overridden by supplying them as arguments.
#'
#' Conditional weighted residuals (CWRES) require some extra steps to
#' calculate. See \code{\link{compute.cwres}} for details.
#'
#' A wide array of extra options controlling bwplots are available. See
#' \code{\link{xpose.plot.bw}} and \code{\link{xpose.panel.bw}} for details.
#'
#' @param object An xpose.data object.
#' @param \dots Other arguments passed to \code{link{xpose.plot.bw}}.
#' @return Returns a box-and-whisker plot of CWRES vs PRED.
#' @author E. Niclas Jonsson, Mats Karlsson, Andrew Hooker & Justin Wilkins
#' @seealso \code{\link{xpose.plot.bw}}, \code{\link{xpose.panel.bw}},
#' \code{\link[lattice]{bwplot}}, \code{\link{xpose.prefs-class}},
#' \code{\link{compute.cwres}}, \code{\link{xpose.data-class}}
#' @keywords methods
#' @examples
#' ## Here we load the example xpose database
#' xpdb <- simpraz.xpdb
#'
#' cwres.vs.pred.bw(xpdb)
#'
#' @export cwres.vs.pred.bw
#' @family specific functions
cwres.vs.pred.bw <-
function(object,
#main = NULL,
#xlb = NULL,
#ylb = NULL,
#onlyfirst=FALSE,
#inclZeroWRES=FALSE,
#subset=xsubset(object),
#mirror=FALSE,
#seed = NULL,
#bins = 10,
#samp = NULL,
...) {
## check for arguments in function
if(is.null(check.vars(c("cwres","pred"),
object,silent=FALSE))) {
return()
}
xplot <- xpose.plot.bw(xvardef("cwres",object),
xvardef("pred",object),
#xlb = xlb,
#ylb = ylb,
#scales=list(cex=0.5,tck=0.5),
#aspect="fill",
object,#main=list(main,cex=0.7),
#main = main,
#bins=bins,
#ids=FALSE,
binvar = xvardef("pred",object),
#xvar = xvardef("cwres",object),
#subset=subset,
...)
return(xplot)
}
| /scratch/gouwar.j/cran-all/cranData/xpose4/R/cwres.vs.pred.bw.R |
#' Weighted residuals (WRES) and conditional WRES (CWRES) plotted against the
#' independent variable (IDV)
#'
#' A graphical comparison between the WRES and CWRES as plotted against the
#' independent variable. Conditional weighted residuals (CWRES) require
#' some extra steps to calculate. Either add \code{CWRES} to your NONMEM
#' table files or compute them using the information proveded in
#' \code{\link{compute.cwres}}. A wide array of extra options controlling
#' xyplots are available. See \code{\link{xpose.plot.default}} and
#' \code{\link{xpose.panel.default}} for details.
#'
#' @param object An xpose.data object.
#' @param ylb A string giving the label for the y-axis. \code{NULL} if none.
#' @param abline Vector of arguments to the \code{\link[lattice]{panel.abline}}
#' function. No abline is drawn if \code{NULL}.
#' @param smooth A \code{NULL} value indicates that no superposed line should
#' be added to the graph. If \code{TRUE} then a smooth of the data will be
#' superimposed.
#' @param scales scales is passed to \code{\link{xpose.plot.default}}.
#' @param \dots Other arguments passed to \code{\link{xpose.plot.default}}.
#' @return A compound xyplot.
#' @author Niclas Jonsson & Andrew Hooker
#' @seealso \code{\link{xpose.plot.default}},
#' \code{\link{xpose.panel.default}}, \code{\link[lattice]{xyplot}},
#' \code{\link{xpose.prefs-class}}, \code{\link{xpose.data-class}},
#' \code{\link{compute.cwres}}
#' @family specific functions
#' @examples
#' cwres.wres.vs.idv(simpraz.xpdb)
#' @export
cwres.wres.vs.idv <-
function(object,
ylb = "Residuals",
abline = c(0,0),
smooth=TRUE,
scales=list(),
...) {
## Make sure we have the necessary variables defined in the
## object.
if(is.null(check.vars(c("idv","cwres","wres"),object))) {
return(NULL)
}
## set scales
if(is.null(scales$x$relation)) scales$x$relation="same"
xplot <- xpose.plot.default(xvardef("idv",object),
c(xvardef("cwres",object),
xvardef("wres",object)),
object,
scales=scales,
ylb=ylb,
abline=abline,
smooth=smooth,
...)
return(xplot)
}
| /scratch/gouwar.j/cran-all/cranData/xpose4/R/cwres.wres.vs.idv.R |
#' Weighted residuals (WRES) and conditional WRES (CWRES) plotted against the
#' population predictions (PRED)
#'
#' Graphically compares WRES and CWRES as plotted against the
#' population predictions.Conditional weighted residuals (CWRES) require
#' some extra steps to calculate. Either add \code{CWRES} to your NONMEM
#' table files or compute them using the information proveded in
#' \code{\link{compute.cwres}}. A wide array of extra options controlling
#' xyplots are available. See \code{\link{xpose.plot.default}} and
#' \code{\link{xpose.panel.default}} for details.
#'
#' @param object An xpose.data object.
#' @param ylb A string giving the label for the y-axis. \code{NULL} if none.
#' @param abline Vector of arguments to the \code{\link[lattice]{panel.abline}}
#' function. No abline is drawn if \code{NULL}.
#' @param smooth A \code{NULL} value indicates that no superposed line should
#' be added to the graph. If \code{TRUE} then a smooth of the data will be
#' superimposed.
#' @param scales scales is passed to \code{\link{xpose.plot.default}}
#' @param \dots Other arguments passed to \code{\link{xpose.plot.default}}.
#' @return A compound xyplot.
#' @author Niclas Jonsson & Andrew Hooker
#' @seealso \code{\link{xpose.plot.default}},
#' \code{\link{xpose.panel.default}}, \code{\link[lattice]{xyplot}},
#' \code{\link{xpose.prefs-class}}, \code{\link{xpose.data-class}},
#' \code{\link{compute.cwres}}
#' @examples
#' cwres.wres.vs.pred(simpraz.xpdb)
#' @export
#' @family specific functions
cwres.wres.vs.pred <-
function(object,
ylb = "Residuals",
abline = c(0,0),
smooth=TRUE,
scales=list(),
...) {
## Make sure we have the necessary variables defined in the
## object.
if(is.null(check.vars(c("pred","cwres","wres"),object))) {
return(NULL)
}
## set scales
if(is.null(scales$x$relation)) scales$x$relation="same"
xplot <- xpose.plot.default(xvardef("pred",object),
c(xvardef("cwres",object),
xvardef("wres",object)),
object,
scales=scales,
ylb=ylb,
abline=abline,
smooth=smooth,
...)
return(xplot)
}
| /scratch/gouwar.j/cran-all/cranData/xpose4/R/cwres.wres.vs.pred.R |
# Xpose 4
# An R-based population pharmacokinetic/
# pharmacodynamic model building aid for NONMEM.
# Copyright (C) 1998-2004 E. Niclas Jonsson and Mats Karlsson.
# Copyright (C) 2005-2008 Andrew C. Hooker, Justin J. Wilkins,
# Mats O. Karlsson and E. Niclas Jonsson.
# Copyright (C) 2009-2010 Andrew C. Hooker, Mats O. Karlsson and
# E. Niclas Jonsson.
# This file is a part of Xpose 4.
# Xpose 4 is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public License
# as published by the Free Software Foundation, either version 3
# of the License, or (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
# You should have received a copy of the GNU Lesser General Public License
# along with this program. A copy can be cound in the R installation
# directory under \share\licenses. If not, see http://www.gnu.org/licenses/.
#' Change in individual objective function value vs. covariate value.
#'
#' Change in individual objective function value vs. covariate value.
#'
#'
#' @param xpdb1 Xpose data object for first NONMEM run
#' @param xpdb2 Xpose data object for second NONMEM run
#' @param covariates Covariates to plot against
#' @param ylb Label for Y axis.
#' @param main Title of plot.
#' @param smooth Should we have a smooth?
#' @param abline abline description.
#' @param ablcol color of abline
#' @param abllwd line width of abline
#' @param abllty type of abline
#' @param max.plots.per.page Plots per page.
#' @param \dots additional arguments to function
#' @author Andrew C. Hooker
#' @keywords methods
#' @examples
#'
#' \dontrun{
#' ## read in table files
#' xpdb8 <- xpose.data(8)
#' xpdb11 <- xpose.data(11)
#'
#' ## Make some plots
#' dOFV.vs.cov(xpdb8,xpdb11,"AGE")
#' dOFV.vs.cov(xpdb8,xpdb11,c("AGE","SECR"))
#' }
#'
#' @export dOFV.vs.cov
#' @family specific functions
dOFV.vs.cov <-
function(xpdb1,
xpdb2,
covariates=xvardef("covariates",xpdb1),
#sig.drop=-3.84,
##decrease.label.number=3,
##increase.label.number=3,
##id.lab.cex=0.6,
##id.lab.pos=2,
#type="p",
#xlb="Covariate",
ylb=expression(paste(Delta, OFV[i])),
main="Default",
#sig.line.col = "red",
#sig.line.lty = "dotted",
##tot.line.col = "grey",
##tot.line.lty = "dashed",
#key=list(#title = expression(paste("Individual influence on ",Delta,"OFV")),
# columns = 1,
# lines = list(pch = c(super.sym$pch[1:2],NA,NA),
# type=list("o","o","l","l"),
# col = c(super.sym$col[1:2],sig.line.col,tot.line.col),
# lty = c(super.sym$lty[1:2],sig.line.lty,tot.line.lty)
# ),
## points = list(pch = c(super.sym$pch[1:2],NA),
## col = c(super.sym$col[1:2],"red")),
# text = list(c(
# expression(paste(Delta, OFV[i] < 0)),
# expression(paste(Delta, OFV[i] > 0)),
# expression(paste("Significant ",Delta, OFV)),
# expression(paste("Total ",Delta, OFV))
##"Individuals with OFV drop",
##"Individuals with OFV increase",
##"Significant drop in ")
# )),
##space="right",
# corner=c(0.95,0.5),border=T
#),
smooth=TRUE,
abline=c(0,0),
ablcol="grey",
abllwd=2,
abllty="dashed",
max.plots.per.page=1,
...)
{
if(is.null(xpdb2)){
cat("Comparison database needed for this plot!")
return(NULL)
}
#require(graphics)
iv1 <- [email protected]
##str(iv2)
iv2 <- [email protected]
##str(iv2)
if(!all(iv1$ID == iv2$ID)){
cat("All ID labels for both databases must match\n")
return(NULL)
}
comp.frame <- data.frame(id=iv1$ID,obj1=iv1$OBJ,obj2=iv2$OBJ)
comp.frame$d.obj <- comp.frame$obj2 - comp.frame$obj1
##str(comp.frame)
##hist(comp.frame$d.obj)
## add to dataframe
xpdb1@Data[!duplicated(xpdb1@Data[,xvardef("id",xpdb1)]),"d.obj"] <- comp.frame$d.obj
xpdb1@Prefs@Labels$d.obj <- "Change in individual OFV"
## str(xpdb1)
##xpdb1@Data[1:10,]
##covariate
## create list for plots
cat.covs <- c()
cont.covs <- c()
for (i in covariates) {
if(is.factor(xpdb1@Data[[i]])){
cat.covs <- c(cat.covs,i)
}else{
cont.covs <- c(cont.covs,i)
}
}
#number.of.plots <- 0
#if(length(cat.covs)>0) number.of.plots <- number.of.plots +1
#if(length(cont.covs)>0) number.of.plots <- number.of.plots +1
cov.list <- list(cont.covs=cont.covs,cat.covs=cat.covs)
if(is.null(cat.covs)) cov.list$cat.covs <- NULL
if(is.null(cont.covs)) cov.list$cont.covs <- NULL
plotList <- vector("list",length(cov.list))
plot.num <- 0 # initialize plot number
for (j in 1:length(cov.list)) {
xplot <- xpose.plot.default(cov.list[[j]],
"d.obj",
xpdb1,
onlyfirst=T,
inclZeroWRES=T,
smooth=smooth,
abline=c(0,0),
ablcol=ablcol,
abllwd=abllwd,
abllty=abllty,
ylb=ylb,
main=NULL,
pass.plot.list=TRUE,
...)
plot.num <- plot.num+1
plotList[[plot.num]] <- xplot
}
default.plot.title <- paste("Individual change in OFV vs. Covariate(s)\n",
"(Run",xpdb2@Runno," - Run",xpdb1@Runno,")",sep="" )
plotTitle <- xpose.multiple.plot.title(object=xpdb1,
plot.text = default.plot.title,
main=main,
no.runno=T,
...)
obj <- xpose.multiple.plot(plotList,plotTitle,max.plots.per.page=max.plots.per.page,
...)
return(obj)
}
| /scratch/gouwar.j/cran-all/cranData/xpose4/R/dOFV.vs.cov.R |
# Xpose 4
# An R-based population pharmacokinetic/
# pharmacodynamic model building aid for NONMEM.
# Copyright (C) 1998-2004 E. Niclas Jonsson and Mats Karlsson.
# Copyright (C) 2005-2008 Andrew C. Hooker, Justin J. Wilkins,
# Mats O. Karlsson and E. Niclas Jonsson.
# Copyright (C) 2009-2010 Andrew C. Hooker, Mats O. Karlsson and
# E. Niclas Jonsson.
# This file is a part of Xpose 4.
# Xpose 4 is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public License
# as published by the Free Software Foundation, either version 3
# of the License, or (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
# You should have received a copy of the GNU Lesser General Public License
# along with this program. A copy can be cound in the R installation
# directory under \share\licenses. If not, see http://www.gnu.org/licenses/.
#' Change in Objective function value vs. removal of individuals.
#'
#' A plot showing the most and least influential individuals in determining a
#' drop in OFV between two models.
#'
#'
#' @param xpdb1 Xpose data object for first NONMEM run ("new" run)
#' @param xpdb2 Xpose data object for Second NONMEM run ("reference" run)
#' @param sig.drop What is a significant drop of OFV?
#' @param decrease.label.number How many points should bw labeled with ID
#' values for those IDs with a drop in iOFV?
#' @param increase.label.number How many points should bw labeled with ID
#' values for those IDs with an increase in iOFV?
#' @param id.lab.cex Size of ID labels.
#' @param id.lab.pos ID label position.
#' @param type Type of lines.
#' @param xlb X-axis label.
#' @param ylb Y-axis label.
#' @param main Title of plot.
#' @param sig.line.col Significant OFV drop line color.
#' @param sig.line.lty Significant OFV drop line type.
#' @param tot.line.col Total OFV drop line color.
#' @param tot.line.lty Total OFV drop line type.
#' @param key Legend for plot.
#' @param \dots Additional arguments to function.
#' @author Andrew C. Hooker
#' @keywords methods
#' @examples
#'
#' \dontrun{
#' library(xpose4)
#'
#' ## first make sure that the iofv values are read into xpose
#' cur.dir <- getwd()
#' setwd(paste(cur.dir,"/LAG_TIME",sep=""))
#' xpdb1 <- xpose.data(1)
#' setwd(paste(cur.dir,"/TRANSIT_MODEL",sep=""))
#' xpdb2 <- xpose.data(1)
#' setwd(cur.dir)
#'
#' ## then make the plot
#' dOFV.vs.id(xpdb1,xpdb2)
#' }
#'
#' @export dOFV.vs.id
#' @family specific functions
dOFV.vs.id <-
function(xpdb1,
xpdb2,
sig.drop=-3.84,
decrease.label.number=3,
increase.label.number=3,
id.lab.cex=0.6,
id.lab.pos=2,
type="o",
xlb="Number of subjects removed",
ylb=expression(paste(Delta,"OFV")),
main="Default",
sig.line.col = "red",
sig.line.lty = "dotted",
tot.line.col = "grey",
tot.line.lty = "dashed",
key=list(#title = expression(paste("Individual influence on ",Delta,"OFV")),
columns = 1,
lines = list(pch = c(super.sym$pch[1:2],NA,NA),
type=list("o","o","l","l"),
col = c(super.sym$col[1:2],sig.line.col,tot.line.col),
lty = c(super.sym$lty[1:2],sig.line.lty,tot.line.lty)
),
## points = list(pch = c(super.sym$pch[1:2],NA),
## col = c(super.sym$col[1:2],"red")),
text = list(c(
expression(paste(Delta, OFV[i] < 0)),
expression(paste(Delta, OFV[i] > 0)),
expression(paste("Significant ",Delta, OFV)),
expression(paste("Total ",Delta, OFV))
##"Individuals with OFV drop",
##"Individuals with OFV increase",
##"Significant drop in ")
)),
##space="right",
corner=c(0.95,0.5),border=T
),
...)
{
if(is.null(xpdb2)){
cat("Comparison database needed for this plot!")
return(NULL)
}
#require(graphics)
iv1 <- [email protected]
##str(iv2)
iv2 <- [email protected]
##str(iv2)
if(!all(iv1$ID == iv2$ID)){
cat("All ID labels for both databases must match\n")
return(NULL)
}
comp.frame <- data.frame(id=iv1$ID,obj1=iv1$OBJ,obj2=iv2$OBJ)
# fix for R version 3.1.0
if(is.factor(comp.frame$obj1)) comp.frame$obj1 <- as.numeric(levels(comp.frame$obj1))[comp.frame$obj1]
if(is.factor(comp.frame$obj2)) comp.frame$obj2 <- as.numeric(levels(comp.frame$obj2))[comp.frame$obj2]
comp.frame$d.obj <- comp.frame$obj2 - comp.frame$obj1
##str(comp.frame)
##hist(comp.frame$d.obj)
ofv1 <- sum(comp.frame$obj1)
ofv2 <- sum(comp.frame$obj2)
d.ofv <- sum(comp.frame$d.obj)
##ofv1
##ofv2
##d.ofv
##ofv2-ofv1
comp.frame$rnk <- rank(comp.frame$d.obj,ties.method="random")
##comp.frame[comp.frame$rnk==74,]
##comp.frame[comp.frame$rnk==1,]
max.rank <- max(comp.frame$rnk)
id.increase <- c(NA)
id.decrease<- c(NA)
increase.sum <- c(d.ofv)
decrease.sum <- c(d.ofv)
for(i in 1:max.rank){
##i=1
## compute largest decrease
tmp <- comp.frame[comp.frame$rnk==i,]
if(tmp$d.obj<=0){
id.decrease <- c(id.decrease,tmp$id)
decrease.sum <- c(decrease.sum,sum(comp.frame[comp.frame$rnk > i,"d.obj"]))
}
## compute largest increase
tmp <- comp.frame[comp.frame$rnk==(max.rank-i+1),]
if(tmp$d.obj>0){
id.increase <- c(id.increase,tmp$id)
increase.sum <- c(increase.sum,
sum(comp.frame[comp.frame$rnk < (max.rank - i +1),"d.obj"]))
}
}
##length(id.increase)
##length(id.decrease)
n.removed <- c(1:max(length(id.increase),length(id.decrease)))-1
##n.removed
if(length(id.increase) < length(n.removed)){
n.na <- length(n.removed) - length(id.increase)
id.increase <- c(id.increase,rep(NA,times=n.na))
increase.sum <- c(increase.sum,rep(NA,times=n.na))
}
if(length(id.decrease) < length(n.removed)){
n.na <- length(n.removed) - length(id.decrease)
id.decrease <- c(id.decrease,rep(NA,times=n.na))
decrease.sum <- c(decrease.sum,rep(NA,times=n.na))
}
plot.frame <- data.frame(n.removed,
id.increase,
increase.sum,
id.decrease,
decrease.sum)
##plot.frame
default.plot.title <- paste("Individual influence on change in OFV\n",
"(Run",xpdb2@Runno," - Run",xpdb1@Runno,")",sep="" )
plotTitle <- xpose.multiple.plot.title(object=xpdb1,
plot.text = default.plot.title,
main=main,
no.runno=T,
...)
##id label
idlab.decrease <- subset(plot.frame,n.removed > 0 & n.removed <= decrease.label.number)
idlab.increase <- subset(plot.frame,n.removed > 0 & n.removed <= increase.label.number)
super.sym <- trellis.par.get("superpose.symbol")
xplot <- xyplot(decrease.sum+increase.sum~n.removed,data=plot.frame,
type=type,
xlab=xlb,
ylab=ylb,
sig.line.col = sig.line.col,
sig.line.lty = sig.line.lty,
tot.line.col = tot.line.col,
tot.line.lty = tot.line.lty,
id.lab.cex = id.lab.cex,
id.lab.pos = id.lab.pos,
panel=function(x,y,
sig.line.col,sig.line.lty,
tot.line.col,tot.line.lty,
id.lab.cex,id.lab.pos,
...){
panel.xyplot(x,y,...)
panel.abline(h=sig.drop,col=sig.line.col,lty=sig.line.lty,...)
panel.abline(h=y[1],col=tot.line.col,lty=tot.line.lty,...)
ltext(x=idlab.decrease$n.removed,y=idlab.decrease$decrease.sum,
label=idlab.decrease$id.decrease,
cex=id.lab.cex,
pos=id.lab.pos,
#adj=c(2,1),
...)
ltext(x=idlab.increase$n.removed,y=idlab.increase$increase.sum,
label=idlab.increase$id.increase,
cex=id.lab.cex,
pos=id.lab.pos,
#adj=c(2,1),
...)
},
##auto.key =T
main= plotTitle,
key = key,
...
)
return(xplot)
}
| /scratch/gouwar.j/cran-all/cranData/xpose4/R/dOFV.vs.id.R |
# Xpose 4
# An R-based population pharmacokinetic/
# pharmacodynamic model building aid for NONMEM.
# Copyright (C) 1998-2004 E. Niclas Jonsson and Mats Karlsson.
# Copyright (C) 2005-2008 Andrew C. Hooker, Justin J. Wilkins,
# Mats O. Karlsson and E. Niclas Jonsson.
# Copyright (C) 2009-2010 Andrew C. Hooker, Mats O. Karlsson and
# E. Niclas Jonsson.
# This file is a part of Xpose 4.
# Xpose 4 is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public License
# as published by the Free Software Foundation, either version 3
# of the License, or (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
# You should have received a copy of the GNU Lesser General Public License
# along with this program. A copy can be cound in the R installation
# directory under \share\licenses. If not, see http://www.gnu.org/licenses/.
#' Change in individual objective function value 1 vs. individual objective
#' function value 2.
#'
#' Change in individual objective function value 1 vs. individual objective
#'
#'
#' @param xpdb1 Xpose data object for first NONMEM run
#' @param xpdb2 Xpose data object for second NONMEM run
#' @param xpdb3 Xpose data object for third NONMEM run
#' @param ylb Label for Y axis.
#' @param xlb Label for X axis.
#' @param main Title of plot.
#' @param smooth Should we have a smooth?
#' @param abline abline description.
#' @param ablcol color of abline
#' @param abllwd line width of abline
#' @param abllty type of abline
#' @param lmline Linear regression line?
#' @param \dots Additional arguments to function.
#' @author Andrew C. Hooker
#' @keywords methods
#' @examples
#'
#' \dontrun{
#' ## read in table files
#' xpdb8 <- xpose.data(8)
#' xpdb8 <- xpose.data(9)
#' xpdb11 <- xpose.data(11)
#'
#' ## Make the plot
#' dOFV.vs.cov(xpdb8,xpdb9,xpdb11)
#' }
#'
#' @export dOFV1.vs.dOFV2
#' @family specific functions
dOFV1.vs.dOFV2 <-
function(xpdb1,
xpdb2,
xpdb3,
##covariates=xvardef("covariates",xpdb1),
#sig.drop=-3.84,
##decrease.label.number=3,
##increase.label.number=3,
##id.lab.cex=0.6,
##id.lab.pos=2,
#type="p",
#xlb="Covariate",
ylb=expression(paste(Delta, OFV1[i])),
xlb=expression(paste(Delta, OFV2[i])),
main="Default",
#sig.line.col = "red",
#sig.line.lty = "dotted",
##tot.line.col = "grey",
##tot.line.lty = "dashed",
#key=list(#title = expression(paste("Individual influence on ",Delta,"OFV")),
# columns = 1,
# lines = list(pch = c(super.sym$pch[1:2],NA,NA),
# type=list("o","o","l","l"),
# col = c(super.sym$col[1:2],sig.line.col,tot.line.col),
# lty = c(super.sym$lty[1:2],sig.line.lty,tot.line.lty)
# ),
## points = list(pch = c(super.sym$pch[1:2],NA),
## col = c(super.sym$col[1:2],"red")),
# text = list(c(
# expression(paste(Delta, OFV[i] < 0)),
# expression(paste(Delta, OFV[i] > 0)),
# expression(paste("Significant ",Delta, OFV)),
# expression(paste("Total ",Delta, OFV))
##"Individuals with OFV drop",
##"Individuals with OFV increase",
##"Significant drop in ")
# )),
##space="right",
# corner=c(0.95,0.5),border=T
#),
smooth=NULL,
abline=c(0,1),
ablcol="grey",
abllwd=2,
abllty="dashed",
lmline=TRUE,
##max.plots.per.page=1,
...)
{
if(is.null(xpdb2)){
cat("1st Comparison database needed for this plot!")
return(NULL)
}
if(is.null(xpdb3)){
cat("2nd Comparison database needed for this plot!")
return(NULL)
}
iv1 <- [email protected]
##str(iv2)
iv2 <- [email protected]
##str(iv2)
iv3 <- [email protected]
if(!all(iv1$ID == iv2$ID)){
cat("All ID labels for 1st and 2nd databases must match\n")
return(NULL)
}
if(!all(iv1$ID == iv3$ID)){
cat("All ID labels for 1st and 3rd databases must match\n")
return(NULL)
}
comp.frame <- data.frame(id=iv1$ID,obj1=iv1$OBJ,obj2=iv2$OBJ,obj3=iv3$OBJ)
comp.frame$d.obj1 <- comp.frame$obj2 - comp.frame$obj1
comp.frame$d.obj2 <- comp.frame$obj3 - comp.frame$obj1
##str(comp.frame)
##hist(comp.frame$d.obj)
## add to dataframe
xpdb1@Data[!duplicated(xpdb1@Data[,xvardef("id",xpdb1)]),"d.obj1"] <- comp.frame$d.obj1
xpdb1@Data[!duplicated(xpdb1@Data[,xvardef("id",xpdb1)]),"d.obj2"] <- comp.frame$d.obj2
xpdb1@Prefs@Labels$d.obj1 <- "Change in individual OFV 1"
xpdb1@Prefs@Labels$d.obj2 <- "Change in individual OFV 2"
## str(xpdb1)
##xpdb1@Data[1:10,]
##covariate
## create list for plots
## cat.covs <- c()
## cont.covs <- c()
## for (i in covariates) {
## if(is.factor(xpdb1@Data[[i]])){
## cat.covs <- c(cat.covs,i)
## }else{
## cont.covs <- c(cont.covs,i)
## }
## }
##Number.of.plots <- 0
##if(length(cat.covs)>0) number.of.plots <- number.of.plots +1
##if(length(cont.covs)>0) number.of.plots <- number.of.plots +1
#cov.list <- list(cont.covs=cont.covs,cat.covs=cat.covs)
#plotList <- vector("list",length(cov.list))
#plot.num <- 0 # initialize plot number
#for (j in 1:length(cov.list)) {
default.plot.title <- paste("Individual change in OFV1 vs. OFV2\n",
"(OFV 1 = Run",xpdb2@Runno," - Run",xpdb1@Runno,")\n",
"(OFV 2 = Run",xpdb3@Runno," - Run",xpdb1@Runno,")",
sep="" )
plotTitle <- xpose.multiple.plot.title(object=xpdb1,
plot.text = default.plot.title,
main=main,
no.runno=T,
...)
xplot <- xpose.plot.default("d.obj2",
"d.obj1",
xpdb1,
onlyfirst=T,
inclZeroWRES=T,
smooth=NULL,
lmline=lmline,
abline=abline,
ablcol=ablcol,
abllwd=abllwd,
abllty=abllty,
ylb=ylb,
xlb=xlb,
main=plotTitle,
#pass.plot.list=TRUE,
...)
return(xplot)
}
| /scratch/gouwar.j/cran-all/cranData/xpose4/R/dOFV1.vs.dOFV2.R |
#' Check through the source dataset to detect problems
#'
#' This function graphically "checks out" the dataset to identify errors or
#' inconsistencies.
#'
#' This function creates a series of \code{dotplots}, one for each variable in
#' the dataset, against individual ID. Outliers and clusters may easily be
#' detected in this manner.
#'
#' @param obj NULL or an xpose.data object.
#' @param datafile A data file, suitable for import by
#' \code{\link{read.table}}.
#' @param hlin An integer, specifying the line number on which the column
#' headers appear.
#' @param dotcol Colour for the dots in the dotplot. If obj is an xpose data
#' object then the default is to use the same value as defined for
#' box-and-whisker plots.
#' @param dotpch Plotting character for the dots in the dotplot. If obj is an
#' xpose data object then the default is to use the same value as defined for
#' box-and-whisker plots.
#' @param dotcex Relative scaling for the dots in the dotplot. If obj is an
#' xpose data object then the default is to use the same value as defined for
#' box-and-whisker plots.
#' @param idlab The ID column label in the dataset. Input as a text string.
#' @param csv Is the data file in CSV format (comma separated values)? If the
#' value is \code{NULL} then the user is asked at the command line. If
#' supplied to the function the value can be \code{TRUE/FALSE}.
#' @param main The title to the plot. "default" means that Xpose creates a
#' title.
#' @param \dots Other arguments passed to \code{link[lattice]{dotplot}}.
#' @return A stack of dotplots.
#' @author Niclas Jonsson, Andrew Hooker & Justin Wilkins
#' @seealso \code{\link[lattice]{dotplot}}, \code{\link{xpose.prefs-class}},
#' \code{\link{read.table}}
#' @keywords methods
#' @examples
#'
#' \dontrun{
#' ## We expect to find the required NONMEM run, table and data files for run
#' ## 5 in the current working directory
#' xpdb5 <- xpose.data(5)
#'
#' data.checkout(xpdb5, datafile = "mydata.dta")
#' data.checkout(datafile = "mydata.dta")
#' }
#'
#' @export data.checkout
#' @family data functions
#' @family specific functions
"data.checkout"<-
function(obj=NULL,
datafile = ".ask.",
hlin = -99,
dotcol = "black",
dotpch = 16,
dotcex = 1,
idlab="ID",
csv=NULL,
main="Default",
...) {
if (!is.null(obj) &&
missing(dotcol) &&
missing(dotpch) &&
missing(dotcex) ){
dotcol = obj@[email protected]$bwdotcol
dotpch = obj@[email protected]$bwdotpch
dotcex = obj@[email protected]$bwdotcex
}
if (datafile==".ask.") {
cat("Please enter the name of the data file you wish to check:\n")
datafile <- readline()
}
if(is.null(csv)){
cat("Is the data in CSV format? (y/n):\n")
csv <- readline()
if ((csv == "y") ||
(csv == "Y") ||
(csv == "yes") ||
(csv == "YES") ||
(csv == "Yes")) {
csv <- TRUE
} else {
csv <- FALSE
}
}
if(!is.readable.file(datafile)) {
cat("There is no file with that name in the current directory!\n")
return()
}
if (hlin == -99) {
cat("Please enter the line number in the data file\n")
cat("containing the column headers. Note that if you have\n")
cat("commented them out, with a '#', for example, you may get\n")
cat("unpredictable results.) (1): ")
hlin <- readline()
}
if(hlin == "")
hlin <- 1
hlin <- as.numeric(hlin)
if(hlin < 0) {
cat("The line number has to be > 0!\n"
)
invisible()
return()
}
hlin <- hlin - 1
if (csv) {
data <- read.csv(datafile, skip = hlin, header = T)
} else {
data <- read.table(datafile, skip = hlin, header = T)
}
delcol <- grep("XXXX*", names(data))
if(length(delcol) != 0) {
data <- data[, - delcol]
}
tit <- paste("Data set checkout of", datafile)
## create list for plots
number.of.plots <- dim(data)[2] - 1
plotList <- vector("list",number.of.plots)
plot.num <- 0 # initialize plot number
idcol <- match(idlab,names(data))
if(is.na(idcol)) idcol <- 1
#ids <- unique(data[, idcol])
for(j in 1:dim(data)[2]) {
if (j==idcol) next
xlb <- names(data)[j]
ylb <- names(data)[idcol]
xplot <- dotplot(data[, idcol] ~ data[, j],
main = NULL,
scales = list(x = list(cex = 0.7),
y = list(cex = 0.45)),
xlab = xlb,
ylab = ylb,
col = dotcol,
cex = dotcex,
pch = dotpch
)
plot.num <- plot.num+1
plotList[[plot.num]] <- xplot
}
default.plot.title <- tit
plotTitle <- xpose.multiple.plot.title(object=obj,
plot.text = default.plot.title,
main=main,
...)
obj <- xpose.multiple.plot(plotList,plotTitle,...)
return(obj)
}
| /scratch/gouwar.j/cran-all/cranData/xpose4/R/data.checkout.R |
# Xpose 4
# An R-based population pharmacokinetic/
# pharmacodynamic model building aid for NONMEM.
# Copyright (C) 1998-2004 E. Niclas Jonsson and Mats Karlsson.
# Copyright (C) 2005-2008 Andrew C. Hooker, Justin J. Wilkins,
# Mats O. Karlsson and E. Niclas Jonsson.
# Copyright (C) 2009-2010 Andrew C. Hooker, Mats O. Karlsson and
# E. Niclas Jonsson.
# This file is a part of Xpose 4.
# Xpose 4 is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public License
# as published by the Free Software Foundation, either version 3
# of the License, or (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
# You should have received a copy of the GNU Lesser General Public License
# along with this program. A copy can be cound in the R installation
# directory under \share\licenses. If not, see http://www.gnu.org/licenses/.
data.checkout.menu <-
function() {
choices <- c("Return to previous menu ->",
"Numerically summarize the covariates",
"Histograms of the covariates",
"QQ plots of the covariates",
"Scatterplot matrix of covariates",
"Check dataset",
"Observations vs independent variable"
)
title="\nDATA CHECKOUT MENU\n \\main\\data checkout"
pick <- menu(choices,title=title)
qx <- 0
switch(pick+1,
qx <- 2,
qx <- 1,
cov.summary(eval(parse(text=".cur.db"))),
print(cov.hist(eval(parse(text=".cur.db")))),
print(cov.qq(eval(parse(text=".cur.db")))),
print(cov.splom(eval(parse(text=".cur.db")))),
print(data.checkout(obj=eval(parse(text=".cur.db")))), #cat("\nNot defined yet\n"),
print(dv.vs.idv(eval(parse(text=".cur.db")))) #cat("\nNot defined yet\n")
)
if(qx == 2) {
return(invisible(2))
} else {
if(qx == 1) {
return(invisible(0))
} else {
Recall()
}
}
}
| /scratch/gouwar.j/cran-all/cranData/xpose4/R/data.checkout.menu.R |
#' Prints the contents of an Xpose data object
#'
#' These functions print a summary of the specified Xpose object to the R
#' console.
#'
#' These functions return a detailed summary of the contents of a specified
#' \code{\link{xpose.data}} object.
#'
#' @param object An \code{xpose.data} object.
#' @return A detailed summary of the contents of a specified
#' \code{\link{xpose.data}} object.
#' @author Niclas Jonsson & Justin Wilkins
#' @seealso \code{\link{xpose.data}}
#' @keywords methods
#' @examples
#' db.names(simpraz.xpdb)
#'
#' @export
#' @family data functions
db.names<-
function(object)
{
### Displays the name of the current database.
if(exists("object")) {
cat(paste("\nThe current run number is ", object@Runno, ".\n\n", sep=""))
xpose.print(object,long=T)
}
else {
cat("The current run number is", object@Runno,
"but no matching database was found.\n")
}
return()
}
| /scratch/gouwar.j/cran-all/cranData/xpose4/R/db.names.R |
# Xpose 4
# An R-based population pharmacokinetic/
# pharmacodynamic model building aid for NONMEM.
# Copyright (C) 1998-2004 E. Niclas Jonsson and Mats Karlsson.
# Copyright (C) 2005-2008 Andrew C. Hooker, Justin J. Wilkins,
# Mats O. Karlsson and E. Niclas Jonsson.
# Copyright (C) 2009-2010 Andrew C. Hooker, Mats O. Karlsson and
# E. Niclas Jonsson.
# This file is a part of Xpose 4.
# Xpose 4 is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public License
# as published by the Free Software Foundation, either version 3
# of the License, or (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
# You should have received a copy of the GNU Lesser General Public License
# along with this program. A copy can be cound in the R installation
# directory under \share\licenses. If not, see http://www.gnu.org/licenses/.
documentation.menu <-
function(prevPick) {
choices <- c("Return to previous menu ->",
"Change run number",
"Tabulate parameter values",
"Summarize run")
title="\nDOCUMANTATION MENU\n \\main\\documentation model"
pick <- menu(choices,title=title)
qx <- 0
switch(pick+1,
qx <- 2,
qx <- 1,
change.xp.obj(),
tabulate.parameters(eval(parse(text=".cur.db")),prompt=T),
runsum.print(eval(parse(text=".cur.db")))
#runsum.print(eval(parse(text=".cur.db")),new.version=FALSE)
)
if(qx == 2) {
return(invisible(2))
} else {
if(qx == 1) {
return(invisible(0))
} else {
Recall()
}
}
}
| /scratch/gouwar.j/cran-all/cranData/xpose4/R/documentation.menu.R |
#' Observations (DV), individual predictions (IPRED) and population predictions
#' (IPRED) plotted against the independent variable (IDV), for Xpose 4
#'
#' This is a compound plot consisting of plots of observations (DV), individual
#' predictions (IPRED), and population predictions (PRED) against the
#' independent variable (IDV), a specific function in Xpose 4. It is a wrapper
#' encapsulating arguments to the \code{xpose.plot.default} function.
#'
#' A wide array of extra options controlling \code{xyplots} are available. See
#' \code{\link{xpose.plot.default}} and \code{\link{xpose.panel.default}} for
#' details.
#'
#' @param object An xpose.data object.
#' @param ylb A string giving the label for the y-axis. \code{NULL} if none.
#' @param layout A list controlling the number of columns and rows in a
#' compound plot. The default is 2 columns and 1 row.
#' @param smooth Logical value indicating whether an x-y smooth should be
#' superimposed. The default is TRUE.
#' @param scales A list to be used for the \code{scales} argument in
#' \code{xyplot}.
#' @param \dots Other arguments passed to \code{link{xpose.plot.default}}.
#' @return Returns a compound plot comprising plots of observations (DV),
#' individual predictions (IPRED), and population predictions (PRED) against
#' the independent variable (IDV).
#' @author E. Niclas Jonsson, Mats Karlsson, Andrew Hooker & Justin Wilkins
#' @seealso \code{\link{dv.vs.idv}}, \code{\link{ipred.vs.idv}},
#' \code{\link{pred.vs.idv}}, \code{\link{xpose.plot.default}},
#' \code{\link{xpose.panel.default}}, \code{\link[lattice]{xyplot}},
#' \code{\link{xpose.prefs-class}}, \code{\link{xpose.data-class}}
#' @keywords methods
#' @examples
#'
#' ## Here we load the example xpose database
#' xpdb <- simpraz.xpdb
#'
#' dv.preds.vs.idv(xpdb)
#'
#' @export dv.preds.vs.idv
#' @family specific functions
"dv.preds.vs.idv" <-
function(object,
#main = NULL,
ylb = "Observations/Predictions",
#xlb = xlabel(xvardef("idv",object),object),
layout=c(3,1),
#subset = xsubset(object),
#onlyfirst = FALSE,
#inclZeroWRES = FALSE,
smooth=TRUE,
scales=list(),
...)
{
## Make sure we have the necessary variables defined in the
## object.
if(is.null(check.vars(c("id","idv","dv","pred","ipred"),object))) {
return(NULL)
}
if(is.null(scales$x$relation)) scales$x$relation="same"
xplot <- xpose.plot.default(xvardef("idv",object),
c(xvardef("dv",object),
xvardef("ipred",object),
xvardef("pred",object)),
object,
scales=scales,
#xlb=xlb,
ylb=ylb,
#main=main,
layout=layout,
#abline=abline,
#lmline=lmline,
#subset=subset,
smooth=smooth,
...)
return(xplot)
}
| /scratch/gouwar.j/cran-all/cranData/xpose4/R/dv.preds.vs.idv.R |
# Xpose 4
# An R-based population pharmacokinetic/
# pharmacodynamic model building aid for NONMEM.
# Copyright (C) 1998-2004 E. Niclas Jonsson and Mats Karlsson.
# Copyright (C) 2005-2008 Andrew C. Hooker, Justin J. Wilkins,
# Mats O. Karlsson and E. Niclas Jonsson.
# Copyright (C) 2009-2010 Andrew C. Hooker, Mats O. Karlsson and
# E. Niclas Jonsson.
# This file is a part of Xpose 4.
# Xpose 4 is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public License
# as published by the Free Software Foundation, either version 3
# of the License, or (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
# You should have received a copy of the GNU Lesser General Public License
# along with this program. A copy can be cound in the R installation
# directory under \share\licenses. If not, see http://www.gnu.org/licenses/.
#' Observations (DV) plotted against the independent variable (IDV) for Xpose 4
#'
#' This is a plot of observations (DV) vs the independent variable (IDV), a
#' specific function in Xpose 4. It is a wrapper encapsulating arguments to the
#' \code{xpose.plot.default} function. Most of the options take their default
#' values from xpose.data object but may be overridden by supplying them as
#' arguments.
#'
#' A wide array of extra options controlling \code{\link[lattice]{xyplot}} are
#' available. See \code{\link{xpose.plot.default}} and
#' \code{\link{xpose.panel.default}} for details.
#'
#' @param object An xpose.data object.
#' @param smooth Logical value indicating whether an x-y smooth should be
#' superimposed. The default is TRUE.
#' @param \dots Other arguments passed to \code{link{xpose.plot.default}}.
#' @return Returns an xyplot of DV vs IDV.
#' @author E. Niclas Jonsson, Mats Karlsson, Andrew Hooker & Justin Wilkins
#' @seealso \code{\link{xpose.plot.default}},
#' \code{\link{xpose.panel.default}}, \code{\link[lattice]{xyplot}},
#' \code{\link{xpose.prefs-class}}, \code{\link{xpose.data-class}}
#' @keywords methods
#' @examples
#' ## Here we load the example xpose database
#' xpdb <- simpraz.xpdb
#'
#' dv.vs.idv(xpdb)
#'
#' ## A conditioning plot
#' dv.vs.idv(xpdb, by="HCTZ")
#'
#' ## Logarithmic Y-axis
#' dv.vs.idv(xpdb, logy=TRUE)
#'
#' @export dv.vs.idv
#' @family specific functions
dv.vs.idv <-
function(object,
smooth=TRUE,
...) {
## Make sure we have the necessary variables defined in the
## object.
if(is.null(check.vars(c("idv","dv"),object))) {
return(NULL)
}
xplot <- xpose.plot.default(xvardef("idv",object),
xvardef("dv",object),
smooth=smooth,
object,
...)
return(xplot)
}
| /scratch/gouwar.j/cran-all/cranData/xpose4/R/dv.vs.idv.R |
# Xpose 4
# An R-based population pharmacokinetic/
# pharmacodynamic model building aid for NONMEM.
# Copyright (C) 1998-2004 E. Niclas Jonsson and Mats Karlsson.
# Copyright (C) 2005-2008 Andrew C. Hooker, Justin J. Wilkins,
# Mats O. Karlsson and E. Niclas Jonsson.
# Copyright (C) 2009-2010 Andrew C. Hooker, Mats O. Karlsson and
# E. Niclas Jonsson.
# This file is a part of Xpose 4.
# Xpose 4 is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public License
# as published by the Free Software Foundation, either version 3
# of the License, or (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
# You should have received a copy of the GNU Lesser General Public License
# along with this program. A copy can be cound in the R installation
# directory under \share\licenses. If not, see http://www.gnu.org/licenses/.
#' Observations (DV) plotted against individual predictions (IPRED) for Xpose 4
#'
#' This is a plot of observations (DV) vs individual predictions (IPRED), a
#' specific function in Xpose 4. It is a wrapper encapsulating arguments to the
#' \code{xpose.plot.default} function. Most of the options take their default
#' values from xpose.data object but may be overridden by supplying them as
#' arguments.
#'
#' A wide array of extra options controlling \code{\link[lattice]{xyplot}} are
#' available. See \code{\link{xpose.plot.default}} and
#' \code{\link{xpose.panel.default}} for details.
#'
#' @param object An xpose.data object.
#' @param abline Vector of arguments to the \code{\link[lattice]{panel.abline}}
#' function. No abline is drawn if \code{NULL}.
#' @param smooth Logical value indicating whether an x-y smooth should be
#' superimposed. The default is TRUE.
#' @param \dots Other arguments passed to \code{link{xpose.plot.default}}.
#' @return Returns an xyplot of DV vs IPRED.
#' @author E. Niclas Jonsson, Mats Karlsson, Andrew Hooker & Justin Wilkins
#' @seealso \code{\link{xpose.plot.default}},
#' \code{\link{xpose.panel.default}}, \code{\link[lattice]{xyplot}},
#' \code{\link{xpose.prefs-class}}, \code{\link{xpose.data-class}}
#' @keywords methods
#' @examples
#' ## Here we load the example xpose database
#' xpdb <- simpraz.xpdb
#'
#' dv.vs.ipred(xpdb)
#'
#' ## A conditioning plot
#' dv.vs.ipred(xpdb, by="HCTZ")
#'
#' @export dv.vs.ipred
#' @family specific functions
"dv.vs.ipred" <-
function(object,
abline=c(0,1),
smooth=TRUE,
...) {
## check for arguments in function
if(is.null(check.vars(c("dv","ipred"),
object,silent=FALSE))) {
return()
}
xplot <- xpose.plot.default(xvardef("ipred",object),
xvardef("dv",object),
abline=abline,
smooth=smooth,
object,
...)
return(xplot)
}
| /scratch/gouwar.j/cran-all/cranData/xpose4/R/dv.vs.ipred.R |
# Xpose 4
# An R-based population pharmacokinetic/
# pharmacodynamic model building aid for NONMEM.
# Copyright (C) 1998-2004 E. Niclas Jonsson and Mats Karlsson.
# Copyright (C) 2005-2008 Andrew C. Hooker, Justin J. Wilkins,
# Mats O. Karlsson and E. Niclas Jonsson.
# Copyright (C) 2009-2010 Andrew C. Hooker, Mats O. Karlsson and
# E. Niclas Jonsson.
# This file is a part of Xpose 4.
# Xpose 4 is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public License
# as published by the Free Software Foundation, either version 3
# of the License, or (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
# You should have received a copy of the GNU Lesser General Public License
# along with this program. A copy can be cound in the R installation
# directory under \share\licenses. If not, see http://www.gnu.org/licenses/.
#' Dependent variable vs individual predictions, conditioned on covariates, for
#' Xpose 4
#'
#' This is a plot of dependent variable (DV) vs individual predictions (IPRED)
#' conditioned by covariates, a specific function in Xpose 4. It is a wrapper
#' encapsulating arguments to the \code{xpose.plot.default} function. Most of
#' the options take their default values from xpose.data object but may be
#' overridden by supplying them as arguments.
#'
#' Each of the covariates in the Xpose data object, as specified in
#' \code{object@Prefs@Xvardef$Covariates}, is evaluated in turn, creating a
#' stack of plots.
#'
#' A wide array of extra options controlling \code{\link[lattice]{xyplot}} are
#' available. See \code{\link{xpose.plot.default}} and
#' \code{\link{xpose.panel.default}} for details.
#'
#' @param object An xpose.data object.
#' @param abline Vector of arguments to the \code{\link[lattice]{panel.abline}}
#' function. No abline is drawn if \code{NULL}.
#' @param smooth Logical value indicating whether an x-y smooth should be
#' superimposed. The default is TRUE.
#' @param main The title of the plot. If \code{"Default"} then a default title
#' is plotted. Otherwise the value should be a string like \code{"my title"} or
#' \code{NULL} for no plot title.
#' @param covs A vector of covariates to use in the plot. If "Default" the
#' the covariates defined in \code{object@Prefs@Xvardef$Covariates} are used.
#' @param \dots Other arguments passed to \code{link{xpose.plot.default}}.
#' @return Returns a stack of \code{xyplot}s of DV vs IPRED, conditioned on
#' covariates.
#' @author E. Niclas Jonsson, Mats Karlsson, Andrew Hooker & Justin Wilkins
#' @seealso \code{\link{dv.vs.ipred}}, \code{\link{xpose.plot.default}},
#' \code{\link{xpose.panel.default}}, \code{\link[lattice]{xyplot}},
#' \code{\link{xpose.prefs-class}}, \code{\link{xpose.data-class}}
#' @keywords methods
#' @examples
#' dv.vs.ipred.by.cov(simpraz.xpdb, covs=c("HCTZ","WT"), max.plots.per.page=2)
#'
#' @export dv.vs.ipred.by.cov
#' @family specific functions
dv.vs.ipred.by.cov <- function(
object,
covs="Default",
#xlb = NULL,
#ylb = NULL,
#onlyfirst=FALSE,
#inclZeroWRES=FALSE,
#subset=xsubset(object),
#mirror=FALSE,
#seed = NULL,
abline = c(0,1),
#abllwd = object@[email protected]$abllwd,
#abllty = object@[email protected]$abllty,
#ablcol = object@[email protected]$ablcol,
#prompt = FALSE,
smooth=TRUE,
#main=NULL,
#samp = NULL,
#max.plots.per.page=1,
#scales=list(),
#aspect = object@[email protected]$aspect,#"fill"
#mirror.aspect="fill",
#pass.plot.list=FALSE,
#x.cex=NULL,
#y.cex=NULL,
#main.cex=NULL,
main="Default",
...)
{
## Make sure we have the necessary variables defined in the
## object.
if(is.null(check.vars(c("dv","ipred"),object))) return(NULL)
# handle covs argument
if(all(covs == "Default")) {
if(is.null(check.vars(c("covariates"),object))) return(NULL)
covs <- xvardef("covariates", object)
} else {
if(is.null(check.vars(covs,object))) return(NULL)
}
## create plot list
plotList <- vector("list",length(covs))
plot.num <- 0 # initialize plot number
for (i in covs) {
xplot <- xpose.plot.default(xvardef("ipred",object),
xvardef("dv",object),
#xlb = xlb,
#ylb = ylb,
abline=abline,
#abllwd=abllwd,
#scales=scales,
#aspect=aspect,
object,
main=NULL,
by=i,
#subset=subset,
smooth=smooth,
#samp=samp,
pass.plot.list=TRUE,
...)
plot.num <- plot.num+1
plotList[[plot.num]] <- xplot
}
default.plot.title <- paste(xlabel(xvardef("dv",object),object)," vs ",
xlabel(xvardef("ipred",object),object),
sep="")
plotTitle <- xpose.multiple.plot.title(object=object,
plot.text = default.plot.title,
main=main,
...)
obj <- xpose.multiple.plot(plotList,plotTitle,...)
return(obj)
}
| /scratch/gouwar.j/cran-all/cranData/xpose4/R/dv.vs.ipred.by.cov.R |
# Xpose 4
# An R-based population pharmacokinetic/
# pharmacodynamic model building aid for NONMEM.
# Copyright (C) 1998-2004 E. Niclas Jonsson and Mats Karlsson.
# Copyright (C) 2005-2008 Andrew C. Hooker, Justin J. Wilkins,
# Mats O. Karlsson and E. Niclas Jonsson.
# Copyright (C) 2009-2010 Andrew C. Hooker, Mats O. Karlsson and
# E. Niclas Jonsson.
# This file is a part of Xpose 4.
# Xpose 4 is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public License
# as published by the Free Software Foundation, either version 3
# of the License, or (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
# You should have received a copy of the GNU Lesser General Public License
# along with this program. A copy can be cound in the R installation
# directory under \share\licenses. If not, see http://www.gnu.org/licenses/.
#' Dependent variable vs individual predictions, conditioned on independent
#' variable, for Xpose 4
#'
#' This is a plot of the dependent variable (DV) vs individual predictions
#' (IPRED) conditioned by the independent variable, a specific function in
#' Xpose 4. It is a wrapper encapsulating arguments to the
#' \code{xpose.plot.default} function. Most of the options take their default
#' values from xpose.data object but may be overridden by supplying them as
#' arguments.
#'
#' A wide array of extra options controlling \code{xyplot} are available. See
#' \code{\link{xpose.plot.default}} and \code{\link{xpose.panel.default}} for
#' details.
#'
#' @param object An xpose.data object.
#' @param abline Vector of arguments to the \code{\link[lattice]{panel.abline}}
#' function. No abline is drawn if \code{NULL}.
#' @param smooth Logical value indicating whether an x-y smooth should be
#' superimposed. The default is TRUE.
#' @param \dots Other arguments passed to \code{link{xpose.plot.default}}.
#' @return Returns a stack of xyplots of DV vs IPRED, conditioned on the
#' independent variable.
#' @author E. Niclas Jonsson, Mats Karlsson, Andrew Hooker & Justin Wilkins
#' @seealso \code{\link{dv.vs.ipred}}, \code{\link{xpose.plot.default}},
#' \code{\link{xpose.panel.default}}, \code{\link[lattice]{xyplot}},
#' \code{\link{xpose.prefs-class}}, \code{\link{xpose.data-class}}
#' @keywords methods
#' @examples
#' dv.vs.ipred.by.idv(simpraz.xpdb)
#'
#' @export dv.vs.ipred.by.idv
#' @family specific functions
dv.vs.ipred.by.idv <-
function(object,
#xlb = NULL,
#ylb = NULL,
#onlyfirst=FALSE,
#inclZeroWRES=FALSE,
#subset=xsubset(object),
abline=c(0,1),
#abllwd = object@[email protected]$abllwd,
#abllty = object@[email protected]$abllty,
#ablcol = object@[email protected]$ablcol,
#mirror=FALSE,
#seed = NULL,
smooth=TRUE,
...) {
## Make sure we have the necessary variables defined in the
## object.
if(is.null(check.vars(c("dv","ipred","idv"),object))) {
return(NULL)
}
xplot <- xpose.plot.default(xvardef("ipred",object),
xvardef("dv",object),
object,
#main=main,
#xlb = xlb,
#ylb=ylb,
abline=abline,
#abllwd=abllwd,
by=xvardef("idv",object),
#subset=subset,
smooth=smooth,
...)
return(xplot)
}
| /scratch/gouwar.j/cran-all/cranData/xpose4/R/dv.vs.ipred.by.idv.R |
# Xpose 4
# An R-based population pharmacokinetic/
# pharmacodynamic model building aid for NONMEM.
# Copyright (C) 1998-2004 E. Niclas Jonsson and Mats Karlsson.
# Copyright (C) 2005-2008 Andrew C. Hooker, Justin J. Wilkins,
# Mats O. Karlsson and E. Niclas Jonsson.
# Copyright (C) 2009-2010 Andrew C. Hooker, Mats O. Karlsson and
# E. Niclas Jonsson.
# This file is a part of Xpose 4.
# Xpose 4 is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public License
# as published by the Free Software Foundation, either version 3
# of the License, or (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
# You should have received a copy of the GNU Lesser General Public License
# along with this program. A copy can be cound in the R installation
# directory under \share\licenses. If not, see http://www.gnu.org/licenses/.
#' Observations (DV) plotted against population predictions (PRED) for Xpose 4
#'
#' This is a plot of observations (DV) vs population predictions (PRED), a
#' specific function in Xpose 4. It is a wrapper encapsulating arguments to the
#' \code{xpose.plot.default} function. Most of the options take their default
#' values from xpose.data object but may be overridden by supplying them as
#' arguments.
#'
#' A wide array of extra options controlling \code{xyplot}s are available. See
#' \code{\link{xpose.plot.default}} and \code{\link{xpose.panel.default}} for
#' details.
#'
#' @param object An xpose.data object.
#' @param abline Vector of arguments to the \code{\link[lattice]{panel.abline}}
#' function. No abline is drawn if \code{NULL}.
#' @param smooth Logical value indicating whether an x-y smooth should be
#' superimposed. The default is TRUE.
#' @param \dots Other arguments passed to \code{link{xpose.plot.default}}.
#' @return Returns an xyplot of DV vs PRED.
#' @author E. Niclas Jonsson, Mats Karlsson, Andrew Hooker & Justin Wilkins
#' @seealso \code{\link{xpose.plot.default}},
#' \code{\link{xpose.panel.default}}, \code{\link[lattice]{xyplot}},
#' \code{\link{xpose.prefs-class}}, \code{\link{xpose.data-class}}
#' @keywords methods
#' @examples
#' ## Here we load the example xpose database
#' xpdb <- simpraz.xpdb
#'
#' ## A vanilla plot
#' dv.vs.pred(xpdb)
#'
#' ## A conditioning plot
#' dv.vs.pred(xpdb, by="HCTZ")
#'
#' @export dv.vs.pred
#' @family specific functions
dv.vs.pred <-
function(object,
abline=c(0,1),
smooth=TRUE,
...) {
## check for arguments in function
if(is.null(check.vars(c("dv","pred"),
object,silent=FALSE))) {
return()
}
xplot <- xpose.plot.default(xvardef("pred",object),
xvardef("dv",object),
abline=abline,
smooth=smooth,
object,
...)
return(xplot)
}
| /scratch/gouwar.j/cran-all/cranData/xpose4/R/dv.vs.pred.R |
# Xpose 4
# An R-based population pharmacokinetic/
# pharmacodynamic model building aid for NONMEM.
# Copyright (C) 1998-2004 E. Niclas Jonsson and Mats Karlsson.
# Copyright (C) 2005-2008 Andrew C. Hooker, Justin J. Wilkins,
# Mats O. Karlsson and E. Niclas Jonsson.
# Copyright (C) 2009-2010 Andrew C. Hooker, Mats O. Karlsson and
# E. Niclas Jonsson.
# This file is a part of Xpose 4.
# Xpose 4 is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public License
# as published by the Free Software Foundation, either version 3
# of the License, or (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
# You should have received a copy of the GNU Lesser General Public License
# along with this program. A copy can be cound in the R installation
# directory under \share\licenses. If not, see http://www.gnu.org/licenses/.
#' Dependent variable vs population predictions, conditioned on covariates, for
#' Xpose 4
#'
#' This is a plot of the dependent variable (DV) vs population predictions
#' (PRED) conditioned by covariates, a specific function in Xpose 4. It is a
#' wrapper encapsulating arguments to the \code{xpose.plot.default} function.
#' Most of the options take their default values from xpose.data object but may
#' be overridden by supplying them as arguments.
#'
#' Each of the covariates in the Xpose data object, as specified in
#' \code{object@Prefs@Xvardef$Covariates}, is evaluated in turn, creating a
#' stack of plots.
#'
#' A wide array of extra options controlling \code{xyplot}s are available. See
#' \code{\link{xpose.plot.default}} and \code{\link{xpose.panel.default}} for
#' details.
#'
#' @inheritParams dv.vs.ipred.by.cov
#' @param object An xpose.data object.
#' @param abline Vector of arguments to the \code{\link[lattice]{panel.abline}}
#' function. No abline is drawn if \code{NULL}.
#' @param smooth Logical value indicating whether an x-y smooth should be
#' superimposed. The default is TRUE.
#' @param main The title of the plot. If \code{"Default"} then a default title
#' is plotted. Otherwise the value should be a string like \code{"my title"} or
#' \code{NULL} for no plot title.
#' @param \dots Other arguments passed to \code{link{xpose.plot.default}}.
#' @return Returns a stack of xyplots of DV vs PRED, conditioned on covariates.
#' @author E. Niclas Jonsson, Mats Karlsson, Andrew Hooker & Justin Wilkins
#' @seealso \code{\link{dv.vs.pred}}, \code{\link{xpose.plot.default}},
#' \code{\link{xpose.panel.default}}, \code{\link[lattice]{xyplot}},
#' \code{\link{xpose.prefs-class}}, \code{\link{xpose.data-class}}
#' @keywords methods
#' @examples
#' dv.vs.pred.by.cov(simpraz.xpdb, covs=c("HCTZ","WT"), max.plots.per.page=2)
#'
#' @export dv.vs.pred.by.cov
#' @family specific functions
dv.vs.pred.by.cov <-
function(object,
covs="Default",
#xlb = NULL,
#ylb = NULL,
#onlyfirst=FALSE,
#inclZeroWRES=FALSE,
#subset=xsubset(object),
#mirror=FALSE,
#seed = NULL,
abline = c(0,1),
#abllwd = object@[email protected]$abllwd,
#abllty = object@[email protected]$abllty,
#ablcol = object@[email protected]$ablcol,
#prompt = FALSE,
smooth=TRUE,
#main=NULL,
#samp = NULL,
#max.plots.per.page=1,
#scales=list(),
#aspect = object@[email protected]$aspect,#"fill"
#mirror.aspect="fill",
#pass.plot.list=FALSE,
#x.cex=NULL,
#y.cex=NULL,
#main.cex=NULL,
main="Default",
...) {
## Make sure we have the necessary variables defined in the
## object.
if(is.null(check.vars(c("dv","ipred"),object))) return(NULL)
# handle covs argument
if(all(covs == "Default")) {
if(is.null(check.vars(c("covariates"),object))) return(NULL)
covs <- xvardef("covariates", object)
} else {
if(is.null(check.vars(covs,object))) return(NULL)
}
## create plot list
plotList <- vector("list",length(covs))
plot.num <- 0 # initialize plot number
for (i in covs) {
xplot <- xpose.plot.default(xvardef("pred",object),
xvardef("dv",object),
#xlb = xlb,
#ylb = ylb,
abline=abline,
#abllwd=abllwd,
#scales=scales,
#aspect=aspect,
object,
main=NULL,
by=i,
#subset=subset,
smooth=smooth,
#samp=samp,
pass.plot.list=TRUE,
...)
plot.num <- plot.num+1
plotList[[plot.num]] <- xplot
}
default.plot.title <- paste(xlabel(xvardef("dv",object),object)," vs ",
xlabel(xvardef("pred",object),object),
sep="")
plotTitle <- xpose.multiple.plot.title(object=object,
plot.text = default.plot.title,
main=main,
...)
obj <- xpose.multiple.plot(plotList,plotTitle,...)
return(obj)
}
| /scratch/gouwar.j/cran-all/cranData/xpose4/R/dv.vs.pred.by.cov.R |
# Xpose 4
# An R-based population pharmacokinetic/
# pharmacodynamic model building aid for NONMEM.
# Copyright (C) 1998-2004 E. Niclas Jonsson and Mats Karlsson.
# Copyright (C) 2005-2008 Andrew C. Hooker, Justin J. Wilkins,
# Mats O. Karlsson and E. Niclas Jonsson.
# Copyright (C) 2009-2010 Andrew C. Hooker, Mats O. Karlsson and
# E. Niclas Jonsson.
# This file is a part of Xpose 4.
# Xpose 4 is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public License
# as published by the Free Software Foundation, either version 3
# of the License, or (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
# You should have received a copy of the GNU Lesser General Public License
# along with this program. A copy can be cound in the R installation
# directory under \share\licenses. If not, see http://www.gnu.org/licenses/.
#' Dependent variable vs population predictions, conditioned on independent
#' variable, for Xpose 4
#'
#' This is a plot of the dependent variable (DV) vs population predictions
#' (PRED) conditioned by the independent variable, a specific function in Xpose
#' 4. It is a wrapper encapsulating arguments to the \code{xpose.plot.default}
#' function. Most of the options take their default values from xpose.data
#' object but may be overridden by supplying them as arguments.
#'
#' A wide array of extra options controlling \code{xyplot}s are available. See
#' \code{\link{xpose.plot.default}} and \code{\link{xpose.panel.default}} for
#' details.
#'
#' @param object An xpose.data object.
#' @param abline Vector of arguments to the \code{\link[lattice]{panel.abline}}
#' function. No abline is drawn if \code{NULL}.
#' @param smooth Logical value indicating whether an x-y smooth should be
#' superimposed. The default is TRUE.
#' @param \dots Other arguments passed to \code{link{xpose.plot.default}}.
#' @return Returns a stack of xyplots of DV vs PRED, conditioned on the
#' independent variable.
#' @author E. Niclas Jonsson, Mats Karlsson, Andrew Hooker & Justin Wilkins
#' @seealso \code{\link{dv.vs.pred}}, \code{\link{xpose.plot.default}},
#' \code{\link{xpose.panel.default}}, \code{\link[lattice]{xyplot}},
#' \code{\link{xpose.prefs-class}}, \code{\link{xpose.data-class}}
#' @keywords methods
#' @examples
#' dv.vs.pred.by.idv(simpraz.xpdb)
#'
#' @export dv.vs.pred.by.idv
#' @family specific functions
dv.vs.pred.by.idv <-
function(object,
#xlb = NULL,
#ylb = NULL,
#onlyfirst=FALSE,
#inclZeroWRES=FALSE,
#subset=xsubset(object),
abline=c(0,1),
#abllwd = object@[email protected]$abllwd,
#abllty = object@[email protected]$abllty,
#ablcol = object@[email protected]$ablcol,
#mirror=FALSE,
#seed = NULL,
smooth=TRUE,
...) {
## Make sure we have the necessary variables defined in the
## object.
if(is.null(check.vars(c("dv","pred","idv"),object))) {
return(NULL)
}
xplot <- xpose.plot.default(xvardef("pred",object),
xvardef("dv",object),
object,
#main=main,
#xlb = xlb,
#ylb=ylb,
abline=abline,
#abllwd=abllwd,
by=xvardef("idv",object),
#subset=subset,
smooth=smooth,
...)
return(xplot)
}
| /scratch/gouwar.j/cran-all/cranData/xpose4/R/dv.vs.pred.by.idv.R |
# Xpose 4
# An R-based population pharmacokinetic/
# pharmacodynamic model building aid for NONMEM.
# Copyright (C) 1998-2004 E. Niclas Jonsson and Mats Karlsson.
# Copyright (C) 2005-2008 Andrew C. Hooker, Justin J. Wilkins,
# Mats O. Karlsson and E. Niclas Jonsson.
# Copyright (C) 2009-2010 Andrew C. Hooker, Mats O. Karlsson and
# E. Niclas Jonsson.
# This file is a part of Xpose 4.
# Xpose 4 is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public License
# as published by the Free Software Foundation, either version 3
# of the License, or (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
# You should have received a copy of the GNU Lesser General Public License
# along with this program. A copy can be cound in the R installation
# directory under \share\licenses. If not, see http://www.gnu.org/licenses/.
#' Observations (DV) are plotted against individual predictions (IPRED) and
#' population predictions (PRED), for Xpose 4
#'
#' This is a compound plot consisting of plots of observations (DV) against
#' individual predictions (IPRED) and population predictions (PRED), a specific
#' function in Xpose 4. It is a wrapper encapsulating arguments to the
#' \code{xpose.plot.default} function.
#'
#' Plots of DV vs PRED and IPRED are presented side by side for comparison.
#'
#' A wide array of extra options controlling \code{xyplot}s are available. See
#' \code{\link{xpose.plot.default}} and \code{\link{xpose.panel.default}} for
#' details.
#'
#' @param object An xpose.data object.
#' @param xlb A string giving the label for the x-axis. \code{NULL} if none.
#' @param layout A list giving the layout of the graphs on the plot, in columns
#' and rows.
#' @param abline Vector of arguments to the \code{\link[lattice]{panel.abline}}
#' function. No abline is drawn if \code{NULL}.
#' @param lmline logical variable specifying whether a linear regression line
#' should be superimposed over an \code{\link[lattice]{xyplot}}. \code{NULL} ~
#' FALSE. (\code{y~x})
#' @param scales A list to be used for the \code{scales} argument in
#' \code{xyplot}.
#' @param smooth \code{NULL} or \code{TRUE} value indicating whether an x-y
#' smooth should be superimposed.
#' @param \dots Other arguments passed to \code{link{xpose.plot.default}}.
#' @return Returns a compound plot comprising plots of observations (DV)
#' against individual predictions (IPRED) and population predictions (PRED).
#' @author E. Niclas Jonsson, Mats Karlsson, Andrew Hooker & Justin Wilkins
#' @seealso \code{\link{dv.vs.pred}}, \code{\link{dv.vs.ipred}},
#' \code{\link{xpose.plot.default}}, \code{\link{xpose.panel.default}},
#' \code{\link[lattice]{xyplot}}, \code{\link{xpose.prefs-class}},
#' \code{\link{xpose.data-class}}
#' @keywords methods
#' @examples
#' dv.vs.pred.ipred(simpraz.xpdb)
#'
#' @export dv.vs.pred.ipred
#' @family specific functions
dv.vs.pred.ipred <-
function(object,
#main = NULL,
xlb = "Predictions",
#ylb = xlabel(xvardef("dv",object),object),
layout=c(2,1),
abline=c(0,1),
lmline=TRUE,
#subset = NULL,
#onlyfirst = FALSE,
#inclZeroWRES = FALSE,
smooth=NULL,
scales=list(),
...) {
## Make sure we have the necessary variables defined in the
## object.
if(is.null(check.vars(c("id","dv","pred","ipred"),object))) {
return(NULL)
}
## set scales
if(is.null(scales$x$relation)) scales$x$relation="same"
xplot <- xpose.plot.default(c(xvardef("pred",object),
xvardef("ipred",object)),
xvardef("dv",object),
object,
scales=scales,
xlb=xlb,
#ylb=ylb,
#main=main,
layout=layout,
abline=abline,
lmline=lmline,
#subset=subset,
smooth=smooth,
...)
return(xplot)
}
| /scratch/gouwar.j/cran-all/cranData/xpose4/R/dv.vs.pred.ipred.R |
# Xpose 4
# An R-based population pharmacokinetic/
# pharmacodynamic model building aid for NONMEM.
# Copyright (C) 1998-2004 E. Niclas Jonsson and Mats Karlsson.
# Copyright (C) 2005-2008 Andrew C. Hooker, Justin J. Wilkins,
# Mats O. Karlsson and E. Niclas Jonsson.
# Copyright (C) 2009-2010 Andrew C. Hooker, Mats O. Karlsson and
# E. Niclas Jonsson.
# This file is a part of Xpose 4.
# Xpose 4 is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public License
# as published by the Free Software Foundation, either version 3
# of the License, or (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
# You should have received a copy of the GNU Lesser General Public License
# along with this program. A copy can be cound in the R installation
# directory under \share\licenses. If not, see http://www.gnu.org/licenses/.
#' @rdname addid
eq.xpose <- function(x, number = 6, overlap = 0.5)
{
X <- sort(x)
if(overlap >= 1) {
m.per.int <- (length(X) + (number - 1) * overlap)/number
m.over <- overlap
}
else {
m.per.int <- length(X)/(number * (1 - overlap) + overlap)
m.over <- overlap * m.per.int
}
left <- round((0:(number - 1)) * (m.per.int - m.over)) + 1
right <- round((1:number) * (m.per.int - m.over) + m.over)
list(lower=X[left], upper=X[right],middle=(X[right]+X[left])/2)
}
| /scratch/gouwar.j/cran-all/cranData/xpose4/R/eq.xpose.R |
#' Exports Xpose graphics settings to a file.
#'
#' This function exports graphics settings for a specified Xpose data object to
#' a file.
#'
#' This function exports the graphics settings (contents of
#' object@[email protected]) for a given \code{xpose.data} object to a file,
#' typically 'xpose.ini'. It is a wrapper for \code{xpose.write}. Note that the
#' file format is not the same as is used in
#' \code{\link{import.variable.definitions}} and
#' \code{\link{export.variable.definitions}}.
#'
#' @aliases export.graph.par xpose.write
#' @param object An \code{xpose.data} object.
#' @param file The file to contain exported Xpose settings.
#' @return Null.
#' @author Niclas Jonsson & Justin Wilkins
#' @seealso \code{\link{import.graph.par}}, \code{\link{xpose.prefs-class}}
#' @keywords methods
#' @examples
#'
#' \dontrun{
#' ## xpdb5 is an Xpose data object
#' ## We expect to find the required NONMEM run and table files for run
#' ## 5 in the current working directory
#' xpdb5 <- xpose.data(5)
#'
#' ## For a filename prompt
#' export.graph.par(xpdb5)
#'
#' ## Command-line driven
#' xpose.write(xpdb5, "c:/XposeSettings/mytheme.ini")
#' }
#'
#' @export
#' @family data functions
export.graph.par <- function(object) {
cat("\nPlease type a filename to export the current graphics settings to.\n")
ans <- readline()
if (ans!="") {
xpose.write(object, file=ans)
} else {
xpose.write(object, file="xpose.ini")
}
return(cat(""))
}
| /scratch/gouwar.j/cran-all/cranData/xpose4/R/export.graph.par.R |
# Xpose 4
# An R-based population pharmacokinetic/
# pharmacodynamic model building aid for NONMEM.
# Copyright (C) 1998-2004 E. Niclas Jonsson and Mats Karlsson.
# Copyright (C) 2005-2008 Andrew C. Hooker, Justin J. Wilkins,
# Mats O. Karlsson and E. Niclas Jonsson.
# Copyright (C) 2009-2010 Andrew C. Hooker, Mats O. Karlsson and
# E. Niclas Jonsson.
# This file is a part of Xpose 4.
# Xpose 4 is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public License
# as published by the Free Software Foundation, either version 3
# of the License, or (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
# You should have received a copy of the GNU Lesser General Public License
# along with this program. A copy can be cound in the R installation
# directory under \share\licenses. If not, see http://www.gnu.org/licenses/.
#' Exports Xpose variable definitions to a file from an Xpose data object.
#'
#' This function exports variable definitions for a specified Xpose data object
#' to a file.
#'
#' This function exports variable definitions (contents of object@Prefs@Xvardef)
#' for a given \code{xpose.data} object to a file, typically
#' 'xpose.vardefs.ini'. Note that file format is not the same as used for
#' graphics settings. It is a wrapper for the R function \code{\link{dput}}.
#'
#' @param object An \code{xpose.data} object.
#' @param file A file name as a string.
#' @return Null.
#' @author Niclas Jonsson & Justin Wilkins
#' @seealso \code{\link{import.variable.definitions}},
#' \code{\link{xpose.prefs-class}} \code{\link{dput}}
#' @keywords methods
#' @examples
#' od = setwd(tempdir()) # move to a temp directory
#' (cur.files <- dir()) # current files in temp directory
#'
#' export.variable.definitions(simpraz.xpdb,file="xpose.vardefs.ini")
#' (new.files <- dir()[!(dir() %in% cur.files)]) # what files are new here?
#'
#' file.remove(new.files) # remove this file
#' setwd(od) # restore working directory
#'
#'
#' @export export.variable.definitions
#' @family data functions
"export.variable.definitions" <- function(object,file="")
{
if(file==""){
cat("Please type a filename to export the current variable definitions to.\n")
cat("Note that backslashes need to be escaped, e.g. \"C:\\\\Xpose\\\".\n")
ans <- readline()
} else {
ans <- file
}
if (ans!="") {
dput(object@Prefs@Xvardef,file=ans)
} else {
dput(object@Prefs@Xvardef,file="xpose.vardefs.ini")
}
return(cat(""))
}
| /scratch/gouwar.j/cran-all/cranData/xpose4/R/export.variable.definitions.R |
"fix.wrapped.lines" <- function(par.mat)
{
## This function unwraps matrix lines that NONMEM and nmsee wraps. Assumes
## no more than 60 etas
nlines <- length(par.mat)
unw.par <- list()
unw.par[[1]] <- par.mat[[1]]
## first line is never wrapped!
if(length(par.mat) == 1) return(unw.par)
unw.line <- 2
doneline <- 0
doneline1 <- 0
doneline2 <- 0
doneline3 <- 0
for(i in 2:nlines) {
if(unw.line <= 12) {
unw.par[[unw.line]] <- par.mat[[i]]
unw.line <- unw.line + 1
} else if(unw.line > 12 && unw.line <= 24) {
if(doneline == i) {
doneline <- 0
next
}
unw.par[[unw.line]] <- c(par.mat[[i]], par.mat[[i + 1]])
unw.line <- unw.line + 1
doneline <- i + 1
}else if(unw.line > 24 && unw.line <= 36) {
if(doneline == i) {
doneline <- 0
next
}
if(doneline1 == i) {
doneline1 <- 0
next
}
unw.par[[unw.line]] <- c(par.mat[[i]],
par.mat[[i +1]],
par.mat[[i + 2]])
unw.line <- unw.line + 1
doneline <- i + 1
doneline1 <- i + 2
}else if(unw.line > 36 && unw.line <= 48) {
if(doneline == i) {
doneline <- 0
next
}
if(doneline1 == i) {
doneline1 <- 0
next
}
if(doneline2 == i) {
doneline2 <- 0
next
}
unw.par[[unw.line]] <- c(par.mat[[i]],
par.mat[[i +1]],
par.mat[[i +2]],
par.mat[[i +3]])
unw.line <- unw.line + 1
doneline <- i + 1
doneline1 <- i + 2
doneline2 <- i + 3
} else if(unw.line > 48 && unw.line <= 60) {
if(doneline == i) {
doneline <- 0
next
}
if(doneline1 == i) {
doneline1 <- 0
next
}
if(doneline2 == i) {
doneline2 <- 0
next
}
if(doneline3 == i) {
doneline3 <- 0
next
}
unw.par[[unw.line]] <- c(par.mat[[i]],
par.mat[[i +1]],
par.mat[[i +2]],
par.mat[[i +3]],
par.mat[[i +4]])
unw.line <- unw.line + 1
doneline <- i + 1
doneline1 <- i + 2
doneline2 <- i + 3
doneline3 <- i + 4
}
}
return(unw.par)
}
| /scratch/gouwar.j/cran-all/cranData/xpose4/R/fix.wrapped.lines.R |
# Xpose 4
# An R-based population pharmacokinetic/
# pharmacodynamic model building aid for NONMEM.
# Copyright (C) 1998-2004 E. Niclas Jonsson and Mats Karlsson.
# Copyright (C) 2005-2008 Andrew C. Hooker, Justin J. Wilkins,
# Mats O. Karlsson and E. Niclas Jonsson.
# Copyright (C) 2009-2010 Andrew C. Hooker, Mats O. Karlsson and
# E. Niclas Jonsson.
# This file is a part of Xpose 4.
# Xpose 4 is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public License
# as published by the Free Software Foundation, either version 3
# of the License, or (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
# You should have received a copy of the GNU Lesser General Public License
# along with this program. A copy can be cound in the R installation
# directory under \share\licenses. If not, see http://www.gnu.org/licenses/.
"gam.change.weights"<-
function(first=TRUE)
{
value <- .cur.db@[email protected]$wts
if (first==TRUE){
cat("Use a weighting factor on parameters (TRUE or FALSE)\n")
if (is.null(value)) {
cat("The current value is NULL...\n")
} else {
cat("The current value is",value,"...\n")
}
cat("\nPlease type the new value ")
}
ans <- readline()
if(ans == "NULL" || ans == "null") {
.cur.db@[email protected]$wts <- NULL
c1<-call("assign",pos = 1, ".cur.db", .cur.db)
eval(c1)
invisible()
return()
} else {
if(ans == "true" || ans == "TRUE") {
.cur.db@[email protected]$wts <- TRUE
c1<-call("assign",pos = 1, ".cur.db", .cur.db)
eval(c1)
invisible()
return()
} else {
if(ans == "false" || ans == "FALSE") {
.cur.db@[email protected]$wts <- FALSE
c1<-call("assign",pos = 1, ".cur.db", .cur.db)
eval(c1)
invisible()
return()
} else {
cat("Please enter TRUE or FALSE ")
Recall(first=FALSE)
}
}
}
}
| /scratch/gouwar.j/cran-all/cranData/xpose4/R/gam.change.weights.R |
# Xpose 4
# An R-based population pharmacokinetic/
# pharmacodynamic model building aid for NONMEM.
# Copyright (C) 1998-2004 E. Niclas Jonsson and Mats Karlsson.
# Copyright (C) 2005-2008 Andrew C. Hooker, Justin J. Wilkins,
# Mats O. Karlsson and E. Niclas Jonsson.
# Copyright (C) 2009-2010 Andrew C. Hooker, Mats O. Karlsson and
# E. Niclas Jonsson.
# This file is a part of Xpose 4.
# Xpose 4 is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public License
# as published by the Free Software Foundation, either version 3
# of the License, or (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
# You should have received a copy of the GNU Lesser General Public License
# along with this program. A copy can be cound in the R installation
# directory under \share\licenses. If not, see http://www.gnu.org/licenses/.
"gam.menu" <-
function() {
choices <- c("Return to previous menu ->",
"Run a GAM",
"Summarize GAM fit",
"Plot GAM results",
"Akaike plot",
"Studentized residuals for GAM fit",
"Individual influence on GAM fit",
"Individual influence on GAM terms",
"Settings for the GAM ->"
)
title="\nGAM MENU\n \\main\\covariate model\\GAM"
pick <- menu(choices,title=title)
qx <- 0
switch(pick+1,
qx <- 2,
qx <- 1,
xp.gam(eval(parse(text=".cur.db")),overwrite=FALSE),
xp.summary(),
print(xp.plot(plot.ids=eval(parse(text=".cur.db"))@[email protected]$plot.ids)),
print(xp.akaike.plot()),
print(xp.ind.stud.res()),
print(xp.ind.inf.fit(plot.ids=eval(parse(text=".cur.db"))@[email protected]$plot.ids)),
print(xp.ind.inf.terms(plot.ids=eval(parse(text=".cur.db"))@[email protected]$plot.ids)),
qx <- gam.settings.menu()
)
if(qx == 2) {
return(invisible(2))
} else {
if(qx == 1) {
return(invisible(0))
} else {
Recall()
}
}
}
| /scratch/gouwar.j/cran-all/cranData/xpose4/R/gam.menu.R |
# Xpose 4
# An R-based population pharmacokinetic/
# pharmacodynamic model building aid for NONMEM.
# Copyright (C) 1998-2004 E. Niclas Jonsson and Mats Karlsson.
# Copyright (C) 2005-2008 Andrew C. Hooker, Justin J. Wilkins,
# Mats O. Karlsson and E. Niclas Jonsson.
# Copyright (C) 2009-2010 Andrew C. Hooker, Mats O. Karlsson and
# E. Niclas Jonsson.
# This file is a part of Xpose 4.
# Xpose 4 is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public License
# as published by the Free Software Foundation, either version 3
# of the License, or (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
# You should have received a copy of the GNU Lesser General Public License
# along with this program. A copy can be cound in the R installation
# directory under \share\licenses. If not, see http://www.gnu.org/licenses/.
"gam.settings.menu"<-
function(){
## Manage GAM setttings
choices <- c("Return to the previous menu ->",
"List current settings",
"Use dispersion factor (yes/no)",
"Use stepwise search (yes/no)",
"Use all lines in data file (yes/no)",
"Change subset expression",
"Normalize to median (on/off)",
"Change covariate scope",
"Weight the parameter values in the GAM search (yes/no)",
"Use ID labels in GAM plots"
)
title="\nGAM SETTINGS MENU\n \\main\\covariate model\\GAM\\settings for the GAM"
pick <- menu(choices,title=title)
qx <- 0
switch(pick+1,
qx <- 2,
qx <- 1,
list.gam.settings(eval(parse(text=".cur.db"))),
change.dispersion(),
change.steppit(),
change.onlyfirst(),
change.subset(eval(parse(text=".cur.db")), classic = T),
change.medianNorm(),
change.xvardef(eval(parse(text=".cur.db")), classic=T, var="covariates"),
gam.change.weights(),
change.use.ids()
)
if(qx == 2) {
return(invisible(2))
} else {
if(qx == 1) {
return(invisible(0))
} else {
Recall()
}
}
}
| /scratch/gouwar.j/cran-all/cranData/xpose4/R/gam.settings.menu.R |
#' @describeIn change_misc_parameters get the documentation field in the Xpose data object.
#' @export
"get.doc" <- function(object, classic=FALSE)
{
if(is.null(doc <- object@Doc)) {
cat("The current database does not contain any documentation.\n")
if (classic == T) {
cat("Do you wish to add some? (y/n)\n")
ans <- readline()
if(ans == "y" || ans == "" || ans == "Y") {
get.doc(object, classic=classic)
}
invisible()
return()
}
}
cat(doc,fill=60)
invisible()
return(cat(""))
}
| /scratch/gouwar.j/cran-all/cranData/xpose4/R/get.doc.R |
# Xpose 4
# An R-based population pharmacokinetic/
# pharmacodynamic model building aid for NONMEM.
# Copyright (C) 1998-2004 E. Niclas Jonsson and Mats Karlsson.
# Copyright (C) 2005-2008 Andrew C. Hooker, Justin J. Wilkins,
# Mats O. Karlsson and E. Niclas Jonsson.
# Copyright (C) 2009-2010 Andrew C. Hooker, Mats O. Karlsson and
# E. Niclas Jonsson.
# This file is a part of Xpose 4.
# Xpose 4 is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public License
# as published by the Free Software Foundation, either version 3
# of the License, or (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
# You should have received a copy of the GNU Lesser General Public License
# along with this program. A copy can be cound in the R installation
# directory under \share\licenses. If not, see http://www.gnu.org/licenses/.
#' @rdname addid
"get.refrunno" <- function(database=".ref.db") {
cat("Please enter the run number you want to compare the current\n")
cat("model with (0 = exit): ")
new.runno <- readline()
if(new.runno == 0) return()
## Check if it exists
if(exists(paste("xpdb", new.runno, sep = ""))) {
cat("A matching database was found. Do you want to use it? (y) (r=recreate) ")
ans <- readline()
if(ans == "y" || ans == "") {
##
## Use old
##
c1<-call("assign",pos = 1, database, eval(as.name(paste("xpdb",
new.runno, sep = ""))))
eval(c1)
return(new.runno)
}
}
##
## Recreate
##
newdb <- xpose.data(new.runno)
if(is.null(newdb)) {
cat("No new database read.\n")
return()
} else {
newnam <- paste("xpdb", new.runno, sep = "")
c2<-call("assign",pos = 1, newnam, newdb)
eval(c2)
c3<-call("assign",pos = 1, database,newdb )
eval(c3)
}
return(new.runno)
}
| /scratch/gouwar.j/cran-all/cranData/xpose4/R/get.refrunno.R |
#' Structured goodness of fit diagnostics.
#'
#' This is a template function for creating structured goodness of fit
#' diagnostics using the functions in the Xpose specific library.
#'
#' The \code{gof} function is provided as a template to facilitate the
#' (structured) use of the functions in the Xpose specific library. Xpose
#' specific is extensively described in the 'Xpose Bestiary'.
#'
#' The function can be renamed so that multiple scripts can be used in
#' parallel.
#'
#' The function is set up to make it easy to display plots on screen as well as
#' to save them in files. In the latter case, plots are save in a sub-directory
#' called 'Plots'.
#'
#' The arguments \code{structural}, \code{residual}, \code{covariate},
#' \code{iiv}, \code{iov} and \code{all} are just "switches" to different parts
#' of the code (if-blocks). These blocks can be removed or the default values
#' of the arguments changed to better suit the needs of the user.
#'
#' It is also possible to add tracing information to the produced plots. This
#' is done via the \code{myTrace} argument. A non-NULL value should be a
#' function that returns a \code{panel.text} object. The default is the
#' \code{xpPage} function that will put a string concatenated from the device
#' name, function name, working directory and date, in small, faint grey, font
#' at the bottom of each graph page. Note that the user need to add
#' \code{page=myTrace} as an argument to the Xpose functions for this to have
#' an effect.
#'
#' The function calls a support function called \code{gofSetup}, which is
#' responsible for setting up the graphics device and determining the file
#' names for saved graphs.
#'
#' @aliases gof gofSetup xpPage
#' @param runno The run number fo Xpose to identify the appropriate files to
#' read. In addition \code{runno} is used to construct the file name to save
#' plots in. \code{runno} can also be \code{NULL} for cases in which the
#' function is used for non-Xpose based code.
#' @param save Logical. \code{TRUE} if the plot(s) is to be saved in a file.
#' \code{FALSE} if the plot(s) is to be displayed on screen. The plot(s) will
#' be saved in a file named with the function name followed by the word 'run',
#' the run number, an order number followed by a file name extension
#' appropriate for the selected \code{saveType}. For example 'gofrun1-01.pdf'
#' for the first plot file created by a script called \code{gof} based on
#' output from run 1 and \code{saveType='pdf'}.
#' @param onefile Logical. \code{TRUE} if plots are to be save in a single file
#' and \code{FALSE} if each plot should be saved as a separate file. In the
#' latter case, each file will be have an incremented order number (01-99).
#' @param saveType The type of graphics file to produce if \code{save=TRUE}.
#' Allowed values are 'pdf' (default), 'wmf' (only Windows) and 'png'.
#' @param pageWidth The width of the graphics device in inches.
#' @param pageHeight The height of the graphics device in inches.
#' @param structural Logical. \code{TRUE} if the code in the structural model
#' section (see below) should be executed and \code{FALSE} if not.
#' @param residual Logical. \code{TRUE} if the code in the residual model
#' section (see below) should be executed and \code{FALSE} if not.
#' @param covariate Logical. \code{TRUE} if the code in the covariate model
#' section (see below) should be executed and \code{FALSE} if not.
#' @param iiv Logical. \code{TRUE} if the code in the IIV model section (see
#' below) should be executed and \code{FALSE} if not.
#' @param iov Logical. \code{TRUE} if the code in the IOV model section (see
#' below) should be executed and \code{FALSE} if not.
#' @param all Logical. \code{TRUE} if the code in all sections (see below)
#' should be executed.
#' @param myTrace \code{NULL} or the name of a function. The value of
#' \code{myTrace} can used with the lattice \code{page=} argument to annotate
#' plots for traceability.
#' @return Does not return anything unless the user specify a return value.
#' @author E. Niclas Jonsson, Mats Karlsson and Andrew Hooker
#' @seealso \code{\link[xpose4]{xpose4-package}}
#' @keywords methods
#' @examples
#'
#' \dontrun{
#' ## This is an example of how the function may be setup by a user.
#'
#' library(xpose4)
#' mygof <- gof
#' fix(mygof)
#'
#' myggof <- function (runno = NULL, save = FALSE, onefile = FALSE, saveType = "pdf",
#' pageWidth = 7.6, pageHeight = 4.9, structural = TRUE, residual = TRUE,
#' covariate = FALSE, iiv = FALSE, iov = FALSE, all = FALSE, myTrace=xpPage) {
#'
#' gofSetup(runno, save, onefile, saveType, pageWidth, pageHeight)
#' xpdb <- xpose.data(runno)
#'
#' if (structural || all) {
#' xplot <- dv.vs.pred.ipred(xpdb, page = myPage)
#' print(xplot)
#' }
#' if (residual || all) {
#' xplot <- absval.wres.vs.pred(xpdb, page = myPage)
#' print(xplot)
#' }
#' if (covariate || all) {
#' }
#' if (iiv || all) {
#' }
#' if (iov || all) {
#' }
#' if (save) dev.off()
#' invisible()
#' }
#'
#' ## The function can then be execute, e.g.:
#' mygof(1)
#'
#' }
#'
#' @export gof
#' @family generic functions
#' @family specific functions
gof <- function(runno=NULL,save=FALSE,onefile=FALSE,
saveType="pdf",pageWidth=7.6,pageHeight=4.9,
structural = TRUE,residual=TRUE,covariate=FALSE,
iiv=FALSE,iov=FALSE,all=FALSE,myTrace=xpPage) {
## This is a template function for creating goodness of fit plots using
## Xpose specific. Type ?gof at the R-prompt for more help.
#########################################################
## Start the graphics device and define save-filenames ##
## (probably no need to change this). ##
#########################################################
gofSetup(runno,save,onefile,saveType,pageWidth,pageHeight)
#############################################
### Set up the data and create the graphs ###
#############################################
## Note! With lattice it is necessary to issue print(plotobject) to
## make the plot appear on the graphics device., e.g.
## xplot <- xyplot(DV~TIME,data)
## print(xplot)
## Read the data and do any modifications
xpdb <- xpose.data(runno)
## Create structural model diagnostics
if(structural || all) {
xplot <- dv.vs.pred.ipred(xpdb,page=myTrace)
print(xplot)
}
## Create residual model diagnostics
if(residual || all) {
xplot <- absval.wres.vs.pred(xpdb,page=NULL)
print(xplot)
}
## Create covariate model diagnostics
if(covariate || all) {
}
## Create iiv model diagnostics
if(iiv || all) {
}
## Create iov model diagnostics
if(iov || all) {
}
#######################
### Finishing tasks ###
#######################
## Turn off device if a file device, i.e. save=TRUE
if(save) dev.off()
invisible()
}
| /scratch/gouwar.j/cran-all/cranData/xpose4/R/gof.R |
# Xpose 4
# An R-based population pharmacokinetic/
# pharmacodynamic model building aid for NONMEM.
# Copyright (C) 1998-2004 E. Niclas Jonsson and Mats Karlsson.
# Copyright (C) 2005-2008 Andrew C. Hooker, Justin J. Wilkins,
# Mats O. Karlsson and E. Niclas Jonsson.
# Copyright (C) 2009-2010 Andrew C. Hooker, Mats O. Karlsson and
# E. Niclas Jonsson.
# This file is a part of Xpose 4.
# Xpose 4 is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public License
# as published by the Free Software Foundation, either version 3
# of the License, or (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
# You should have received a copy of the GNU Lesser General Public License
# along with this program. A copy can be cound in the R installation
# directory under \share\licenses. If not, see http://www.gnu.org/licenses/.
"gof.menu" <- function() {
choices <- c("Return to previous menu ->",
"Basic goodness of fit plots",
"Dependent variables vs predictions",
"Predictions vs independent variable",
"Individual plots",
"Structural model diagnostics ->",
"Residual error model diagnostics ->"
)
title="\nGOODNESS OF FIT PLOTS MENU\n \\main\\goodness of fit plots"
pick <- menu(choices,title=title)
qx <- 0
switch(pick+1,
qx <- 2,
qx <- 1,
print(basic.gof(eval(parse(text=".cur.db")))),
print(dv.vs.pred.ipred(eval(parse(text=".cur.db")))),
print(dv.preds.vs.idv(eval(parse(text=".cur.db")))),
print(ind.plots(eval(parse(text=".cur.db")))),
qx <- structural.diagnostics.menu(),
qx <- residual.diagnostics.menu()
)
if(qx == 2) {
return(invisible(2))
} else {
if(qx == 1) {
return(invisible(0))
} else {
Recall()
}
}
}
| /scratch/gouwar.j/cran-all/cranData/xpose4/R/gof.menu.R |
# Xpose 4
# An R-based population pharmacokinetic/
# pharmacodynamic model building aid for NONMEM.
# Copyright (C) 1998-2004 E. Niclas Jonsson and Mats Karlsson.
# Copyright (C) 2005-2008 Andrew C. Hooker, Justin J. Wilkins,
# Mats O. Karlsson and E. Niclas Jonsson.
# Copyright (C) 2009-2010 Andrew C. Hooker, Mats O. Karlsson and
# E. Niclas Jonsson.
# This file is a part of Xpose 4.
# Xpose 4 is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public License
# as published by the Free Software Foundation, either version 3
# of the License, or (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
# You should have received a copy of the GNU Lesser General Public License
# along with this program. A copy can be cound in the R installation
# directory under \share\licenses. If not, see http://www.gnu.org/licenses/.
gofSetup <- function(runno,save,onefile,saveType,pageWidth,pageHeight) {
## Determine if we are running a Mac so that we can behave appropriately.
isWin <- FALSE
isMac <- FALSE
isLin <- FALSE
if(length(grep("darwin",R.version$os))!=0) { isMac <- TRUE}
if(length(grep("linux",R.version$os))!=0) { isLin <- TRUE}
if(length(grep("mingw",R.version$os))!=0) { isWin <- TRUE}
## Get access to libraries that we need
#library(lattice)
#library(grid)
#library(Hmisc)
#library(xpose4)
## Create file name to store graphs in. The graphs are saved in
## a sub-directory called Plots, which will be created if it doesn't exist
saveDir <- "Plots/"
if(is.na(file.info(saveDir)$isdir)) dir.create(saveDir)
## Create the file name to store graphs in
runnoLabel <- ""
if(!is.null(runno)) runnoLabel <- paste("run",runno,sep="")
saveFileName <- paste(saveDir,sys.calls()[[1]],runnoLabel,
"-%02d.",saveType,sep="")
## Start a device, with recording, the same size as the save file size if we are not saving
if(!save) {
if(isMac) trellis.device(device="quartz", new = FALSE,width=pageWidth,height=pageHeight)
if(isWin) trellis.device(device="windows", new = FALSE,width=pageWidth,height=pageHeight,
record=TRUE)
if(isLin) trellis.device(new = FALSE,width=pageWidth,height=pageHeight)
} else {
if(saveType=="png") png(filename=saveFileName,width=pageWidth,height=pageHeight,res=150,
units="in",bg="white")
if(saveType=="pdf") pdf(file=saveFileName,width=pageWidth,height=pageHeight,
onefile=onefile,bg="white")
if(saveType=="wmf") eval(parse(text=paste("win.metafile(filename=",saveFileName,
",width=",pageWidth,",height=",pageHeight,")",sep="")))
}
}
| /scratch/gouwar.j/cran-all/cranData/xpose4/R/gofSetup.R |
#' Imports Xpose graphics settings from a file to an Xpose data object.
#'
#' This function imports graphics settings for a specified Xpose data object
#' from a file.
#'
#' This function imports graphics settings (contents of
#' object@[email protected]) for a given \code{xpose.data} object from a file,
#' typically 'xpose.ini'. It is a wrapper for \code{xpose.read}. It returns an
#' \code{xpose.data} object. Note that the file format is not the same as is
#' used in \code{\link{import.variable.definitions}} and
#' \code{\link{export.variable.definitions}}.
#'
#' @aliases import.graph.par xpose.read
#' @param object An \code{xpose.data} object.
#' @param classic A logical operator specifying whether the function should
#' assume the classic menu system. This is an internal option and need never be
#' called from the command line.
#' @return An \code{\link{xpose.data}} object (classic = FALSE) or null
#' (classic = TRUE).
#' @author Niclas Jonsson & Justin Wilkins
#' @seealso \code{\link{export.graph.par}}, \code{\link{xpose.prefs-class}}
#' @examples
#'
#' \dontrun{
#' ## xpdb5 is an Xpose data object
#' ## We expect to find the required NONMEM run and table files for run
#' ## 5 in the current working directory
#' xpdb5 <- xpose.data(5)
#'
#' ## Import graphics preferences you saved earlier using export.graph.par
#' xpdb5 <- import.graph.par(xpdb5)
#'
#' ## Command-line driven
#' xpdb5 <- xpose.read(xpdb5, "c:/XposeSettings/mytheme.ini")
#' }
#'
#' @export import.graph.par
#' @family data functions
import.graph.par <- function(object, classic=FALSE) {
cat("\nPlease type a filename to import the current graphics settings from.\n")
cat("Note that backslashes need to be escaped, e.g. \"C:\\\\Xpose\\\\\".\n")
ans <- readline()
if (ans!="") {
if (is.readable.file(ans)) {
xpobj <- xpose.read(object, file=ans)
} else {
cat("This file does not appear to exist, or is unreadable!\n")
return(cat(""))
}
} else {
if (is.readable.file("xpose.ini")) {
xpobj <- xpose.read(object, file="xpose.ini")
cat("Using 'xpose.ini' in the current working directory.\n")
} else {
cat("Using factory settings.\n")
xpobj <- reset.graph.par(object)
}
}
if (classic==TRUE) {
c1<-call("assign",paste("xpdb", object@Runno, sep = ""), data, immediate=T, envir = .GlobalEnv)
eval(c1)
c2<-call("assign",pos = 1, ".cur.db", eval(as.name(paste("xpdb", object@Runno, sep = ""))))
eval(c2)
return(cat(""))
} else {
return(xpobj)
}
}
| /scratch/gouwar.j/cran-all/cranData/xpose4/R/import.graph.par.R |
#' Imports Xpose variable definitions from a file to an Xpose data object.
#'
#' This function imports variable definitions for a specified Xpose data object
#' from a file.
#'
#' This function imports variable definitions (contents of object@Prefs@Xvardef)
#' for a given \code{xpose.data} object from a file, typically
#' 'xpose.vardefs.ini'. It returns an \code{xpose.data} object. Note that file
#' format is not the same as used for graphics settings. It is a wrapper for
#' the R function \code{\link{dget}}.
#'
#' @param object An \code{xpose.data} object.
#' @param classic A logical operator specifying whether the function should
#' assume the classic menu system. This is an internal option and need never be
#' called from the command line.
#' @return An \code{\link{xpose.data}} object (classic == FALSE) or null
#' (classic == TRUE).
#' @author Niclas Jonsson & Justin Wilkins
#' @seealso \code{\link{export.variable.definitions}},
#' \code{\link{xpose.prefs-class}} \code{\link{dget}}
#' @keywords methods
#' @examples
#'
#' \dontrun{
#' ## xpdb5 is an Xpose data object
#' ## We expect to find the required NONMEM run and table files for run
#' ## 5 in the current working directory
#' xpdb5 <- xpose.data(5)
#'
#' xpdb5 <- import.variable.definitions(xpdb5)
#' }
#'
#' @export import.variable.definitions
#' @family data functions
"import.variable.definitions" <- function(object, classic = FALSE)
{
cat("Please type the name of the file that hold the definitions to be\n")
cat("imported. Note that backslashes need to be escaped, e.g. \"C:\\\\Xpose\\\\defs.txt\".\n")
ans <- readline()
data <- object
if(is.readable.file(ans)) {
data@Prefs@Xvardef <- dget(ans)
if (classic==TRUE) {
c1<-call("assign",paste("xpdb", object@Runno, sep = ""), data, immediate=T, envir = .GlobalEnv)
eval(c1)
c2<-call("assign",pos = 1, ".cur.db", eval(as.name(paste("xpdb", object@Runno, sep = ""))))
eval(c2)
return(cat(""))
} else {
return(data)
}
} else {
cat("Couldn't find a file with that name!\n")
return(cat(""))
}
}
| /scratch/gouwar.j/cran-all/cranData/xpose4/R/import.variable.definitions.R |
# Xpose 4
# An R-based population pharmacokinetic/
# pharmacodynamic model building aid for NONMEM.
# Copyright (C) 1998-2004 E. Niclas Jonsson and Mats Karlsson.
# Copyright (C) 2005-2008 Andrew C. Hooker, Justin J. Wilkins,
# Mats O. Karlsson and E. Niclas Jonsson.
# Copyright (C) 2009-2010 Andrew C. Hooker, Mats O. Karlsson and
# E. Niclas Jonsson.
# This file is a part of Xpose 4.
# Xpose 4 is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public License
# as published by the Free Software Foundation, either version 3
# of the License, or (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
# You should have received a copy of the GNU Lesser General Public License
# along with this program. A copy can be cound in the R installation
# directory under \share\licenses. If not, see http://www.gnu.org/licenses/.
#' Observations (DV), individual predictions (IPRED) and population predictions
#' (PRED) are plotted against the independent variable for every individual in
#' the dataset, for Xpose 4
#'
#' This is a compound plot consisting of plots of observations (DV), individual
#' predictions (IPRED) and population predictions (PRED) against the
#' independent variable for every individual in the dataset, a specific
#' function in Xpose 4. It is a wrapper encapsulating arguments to the
#' \code{xpose.plot.default} function.
#'
#' Matrices of individual plots are presented for comparison and closer
#' inspection.
#'
#' @param object An xpose.data object.
#' @param y.vals The Y values to use.
#' @param x.vals The X values to use.
#' @param id.vals The ID values to use.
#' @param key.text The text in the legend to use.
#' @param key Create a legend.
#' @param grid Should the plots have a grid in each plot?
#' @param fill Fill the circles in the points?
#' @param max.plots.per.page Maximum number of plots per page.
#' @param inclZeroWRES Logical value indicating whether rows with WRES=0 is
#' included in the plot. The default is TRUE.
#' @param main The title of the plot. If \code{"Default"} then a default title
#' is plotted. Otherwise the value should be a string like \code{"my title"} or
#' \code{NULL} for no plot title.
#' @param xlb A string giving the label for the x-axis. \code{NULL} if none.
#' @param ylb A string giving the label for the y-axis. \code{NULL} if none.
#' @param layout A list giving the layout of the graphs on the plot, in columns
#' and rows. The default is 4x4.
#' @param subset A string giving the subset expression to be applied to the
#' data before plotting. See \code{\link{xsubset}}.
#' @param type 1-character string giving the type of plot desired. The default
#' is "o", for over-plotted points and lines. See
#' \code{\link{xpose.plot.default}}.
#' @param col A list of three elements, giving plotting characters for
#' observations, individual predictions, and population predictions, in that
#' order. The default is black for DV, red for individual predictions, and blue
#' for population predictions.
#' @param lty A list of three elements, giving line types for observations,
#' individual predictions, and population predictions, in that order.
#' @param lwd A list of three elements, giving line widths for observations,
#' individual predictions, and population predictions, in that order.
#' @param pch A list of three elements, giving plotting characters for
#' observations, individual predictions, and population predictions, in that
#' order.
#' @param cex A list of three elements, giving relative point size for
#' observations, individual predictions, and population predictions, in that
#' order. The default is c(0.7,0.7,0.7).
#' @param prompt Specifies whether or not the user should be prompted to press
#' RETURN between plot pages. Default is TRUE.
#' @param mirror Mirror plots are not yet implemented in this function and this
#' argument must contain a value of \code{NULL}
#' @param main.cex The size of the title.
#' @param pch.ip.sp If there is a panel with just one observation then this
#' specifies the type of points for the DV, IPRED and PRED respectively.
#' @param cex.ip.sp If there is a panel with just one observation then this
#' specifies the size of the points for the DV, IPRED and PRED respectively.
#' @param y.vals.subset Used to subset on the DV, IPRED and PRED variables
#' separately. Either \code{NULL} or a vector of three strings, corresponding
#' to the subset of DV, IPRED and PRED respectively. See examples below.
#' @param \dots Other arguments passed to \code{link{xpose.plot.default}}.
#' @return Returns a stack of plots observations (DV) against individual
#' predictions (IPRED) and population predictions (PRED).
#'
#' A wide array of extra options controlling xyplots are available. See
#' \code{\link{xpose.plot.default}} and \code{\link{xpose.panel.default}} for
#' details.
#' @author E. Niclas Jonsson, Mats Karlsson, Andrew Hooker & Justin Wilkins
#' @seealso \code{\link{xpose.plot.default}},
#' \code{\link{xpose.panel.default}}, \code{\link[lattice]{xyplot}},
#' \code{\link[lattice]{strip.default}}, \code{\link{xpose.prefs-class}},
#' \code{\link{xpose.data-class}}
#' @keywords methods
#' @examples
#' ## Here we load the example xpose database
#' xpdb <- simpraz.xpdb
#'
#' ## Monochrome, suitable for manuscript or report
#' ind.plots(xpdb,
#' subset="ID>40 & ID<57",
#' col=c(1,1,1),
#' lty=c(0,2,3),
#' strip=function(..., bg)
#' strip.default(..., bg="grey"))
#'
#' \dontrun{
#' ## IF we simulate in NONMEM using a dense grid of time points
#' ## and all non-observed DV items are equal to zero.
#' ind.plots(xpdb,inclZeroWRES=TRUE,y.vals.subset=c("DV!=0","NULL","NULL"))
#'
#'
#' # to plot individual plots of multiple variables
#' ind.plots(xpdb,subset="FLAG==1")
#' ind.plots(xpdb,subset="FLAG==2")
#' }
#'
#' @export
#' @family specific functions
ind.plots <-
function(object,
y.vals = c(
xvardef("dv",new.obj),
xvardef("ipred",new.obj),
xvardef("pred",new.obj)
),
x.vals = xvardef("idv",new.obj),
id.vals = xvardef("id",new.obj),
key.text = y.vals,
main = "Default",
key="Default",
xlb = xlabel(xvardef("idv",object),object),
ylb = NULL,
layout = c(4,4),
inclZeroWRES = FALSE,
subset = xsubset(object),
type = "o",
grid=FALSE,
col = c(1,2,4),
lty = c(0,1,3),
lwd = c(1,1,1),
pch = c(21,32,32),
cex = c(0.7,0.7,0.7),
fill=c("lightgrey",0,0),
prompt = FALSE,
mirror=NULL,
main.cex=0.9,
max.plots.per.page=1,
pch.ip.sp=c(21,19,18),
cex.ip.sp=c(0.7,0.4,0.4),
y.vals.subset=NULL,
...){
## check for mirror
if(!is.null(mirror)){
cat("Mirror not currently implemented for individual plots\n")
return()
}
## Make sure we have the necessary variables defined in the ##
## object. ##
if(is.null(check.vars(c("id","idv","dv","ipred","pred"),object))) {
return(NULL)
}
## Bin them
old.obj <- object
old.obj@Data <- Data(object,inclZeroWRES,onlyfirst=FALSE,subset=subset)
if(any(is.null(old.obj@Data))){
return("The subset expression produces no data.")
}
list.id <- sort(unique(old.obj@Data[[xvardef("id",object)]]))
length.id <- length(list.id)
plots.per.page <- layout[1] * layout[2]
plots.cur <- 0
pages <- 1
page.breaks <- c(0)
new.obj <- object
new.obj@Data <- NULL
for (i in list.id) {
plots.cur <- plots.cur + 1
if (plots.cur == plots.per.page) {
pages <- pages + 1
plots.cur <- 0
page.breaks <- c(page.breaks, i)
}
}
if (max(page.breaks) < max(list.id)) {
page.breaks <- c(page.breaks, max(list.id))
}
id.levels <- levels(cut(old.obj@Data[[xvardef("id",object)]], page.breaks, include.lowest=T))
old.obj@Data$bin <- cut(old.obj@Data[[xvardef("id",object)]], page.breaks, include.lowest=T)
plot.num <- 0
plotList <- vector("list",length(id.levels))
for (i in id.levels) {
new.obj@Data <- old.obj@Data[old.obj@Data$bin==i,] #==subset(old.obj@Data, bin == i)
## Set up the data ##
## Figure out what variables we have defined
select <- y.vals
key.text <- key.text
numpans <- length(select)
nobj <- new("xpose.data",
Runno=object@Runno,
Data = NULL)
Data(nobj,keep.structure=T) <- xpose.stack(Data(new.obj,inclZeroWRES=inclZeroWRES,
subset=subset),
new.obj,
select=select,
rep=c(
x.vals,
id.vals
),
subset=y.vals.subset)
# make the ind variable an ordered factor
nobj@Data$ind <- factor(nobj@Data$ind,levels = xlabel(y.vals,new.obj),ordered = T)
## Fix any main and/or axis titles
default.plot.title <- "Individual plots"
plotTitle <- xpose.multiple.plot.title(object=object,
plot.text = default.plot.title,
main=main,
subset=subset,
...)
## Set y axis title
if(is.null(ylb)) {
ylb <- "Observations / Predictions"
}
if(!all(is.na(match(key,"Default")))) {
key=list(text=list(key.text),columns=numpans,
#points=list(pch=pch,cex=cex),
#rectangles=list(pch=pch,cex=cex),
lines=list(lty=lty,pch=pch,cex=cex,col=col,lwd=lwd,size=3,type=type,fill=fill),
between=1)
}
xplot <- xpose.plot.default(x.vals,
"values",
nobj,
by=id.vals,
groups="ind",
iplot=TRUE,
layout=layout,
main=plotTitle,
inclZeroWRES=TRUE,
xlb = xlb,
ylb = ylb,
lty=lty,
col=col,
cex=cex,
grid=grid,
pch=pch,
type=type,
lwd=lwd,
fill=fill,
force.by.factor=TRUE,
ids=F,
as.table=TRUE,
key = key,
subset=subset,
main.cex=main.cex,
force.x.continuous=TRUE,
pch.ip.sp=pch.ip.sp,
cex.ip.sp=cex.ip.sp,
...)
plot.num <- plot.num+1
plotList[[plot.num]] <- xplot
}
obj <- xpose.multiple.plot(plotList,plotTitle=NULL,max.plots.per.page=max.plots.per.page,prompt=prompt,...)
return(obj)
}
| /scratch/gouwar.j/cran-all/cranData/xpose4/R/ind.plots.R |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.