####
# macro for replacing a specified missing value indicator with NA
# within a dataframe
###
setNA <- defmacro(df, var, values,
expr={
df$var[df$var %in% values] <- NA
})
###
# create example data, 999 is missing value indicator
###
d <- data.frame(
Grp=c("Trt", "Ctl", "Ctl", "Trt", "Ctl", "Ctl", "Trt", "Ctl", "Trt", "Ctl"),
V1=c(1, 2, 3, 4, 5, 6, 999, 8, 9, 10),
V2=c(1, 1, 1, 1, 1, 2, 999, 2, 999, 999)
)
d
###
# Try it out
###
setNA(d, V1, 999)
setNA(d, V2, 999)
d
###
# Macro for creating a plotting function
###
plotit <- defmacro( df, var, col="red", title="", expr=
{
plot( df$var ~ df$Grp, type="b", col=col, main=title )
} )
# Notes:
# 1 - The macro expansion of 'col' will correctly replaces the
# object name 'col' (right hand side of col=col) and not the argument
# name (left hand side of col=col) in the function call to plot
# 2 - The plot's y axis label
plotit( d, V1)
plotit( d, V1, "blue" )
# works with variables too
color <- "cyan"
plotit( d, V1, color, title="Crazy Plot")
# An equivalent function is somewhat messier, since it must either explicitly
# construct the y axis label, duplicating some of the work of the plot
# function:
plotit <- function( df, var, col="red", title="" )
{
dname <- deparse(substitute(df))
vname <- deparse(substitute(var))
plot( df[[vname]] ~ df$Grp, type="b", col=col, title=title,
ylab=paste( dname, "$", vname, sep='' ) )
}
# or we explicitly construct the call and then call eval. The code for
# the latter approach is # omiited since this is quite messy and
# requires a lot of work.
Run the code above in your browser using DataLab