[R] Specifying argument values in a function
Sam Albers
tonightsthenight at gmail.com
Fri Aug 26 01:07:15 CEST 2011
Hello all,
I am trying write a fairly simple function that provide a quick way to
calculate several distributions for a data set. I am trying to provide
a function that has a argument that specifies which distribution is
outputted (here "norm" or "cumu"). I also have a melt argument but
that seems to be working fine. I have been able to get my function
working well for just one distribution but when I add another and try
to add a "dist.type" argument (with potential values "cumu" and
"norm"), I get an error message (see below). I am having trouble
finding material that explains how to add an argument that isn't a
TRUE/FALSE situation. Could any explain what I am doing wrong with the
second "distribution specifying" argument? I apologize as I am sure
this is a simple problem but I am just getting my feet wet with this
type of thing in R and am having a little trouble diagnosing the
problem.
#Example below:
library(reshape)
dat <- data.frame(`v1`=runif(6, 0, 125),
`v2`=runif(6, 50, 75),
`v3`=runif(6, 0, 100),
`v4`=runif(6, 0, 200)
)
my.norm <- function(x, melt=TRUE)
{
#Normalized distribution
N.dist <- as.data.frame(sapply(1:length(x), function(i)
(x[[i]]/rowSums(x[,c(1:4)]))*100 ))
norm.melt <- melt.data.frame(N.dist)
if (melt == TRUE) ##Default is a melted data frame
return(norm.melt)
if (melt == FALSE)
return(N.dist)
}
## So this single distribution function works fine
my.norm(dat, melt=TRUE)
my.fun <- function(x, melt=TRUE, dist.type=norm)
{
#Normalized distribution
N.dist <- as.data.frame(sapply(1:length(x), function(i)
(x[[i]]/rowSums(x[,c(1:4)]))*100 ))
norm.melt <- melt.data.frame(N.dist)
if (melt == TRUE && dist.type == norm) ##Default is a melted data frame
return(norm.melt)
if (melt == FALSE && dist.type == norm)
return(N.dist)
## Cumulative distribution
C.dist <- as.data.frame(t(apply(N.dist, 1, cumsum)))
cumu.melt <- melt.data.frame(C.dist)
if (melt == TRUE && dist.type == cumu) ##Default is a melted data frame
return(cumu.melt)
if (melt == FALSE && dist.type == cumu)
return(C.dist)
}
## But this function when used yields two different error messages
depending on the value used for dist.type:
my.fun(dat, melt=TRUE, dist.type = norm)
## Error in dist.type == norm :
## comparison (1) is possible only for atomic and list types
my.fun(dat, melt=TRUE, dist.type = cumu)
## Error in my.fun(dat, dist.type = cumu) : object 'cumu' not found
Thanks in advance!
Sam
More information about the R-help
mailing list