problem with a function
On May 28, 2010, at 12:03 PM, Sarah Goslee wrote:
From your code:
mean <- c(rep(mu0, mzero), rep(mu1,m-mzero)) mean() is a function. If you overwrite it with data, you may mess other things up - any function you call that calls mean will now fail (at best).
Actually, it's bad but not quite that bad.
> mean <- c(1,2,3,4)
> mean(1:10)
[1] 5.5
> mean(mean)
[1] 2.5
> mean[3]
[1] 3
> mean
[1] 1 2 3 4
> apply(matrix(1:100, ncol=10),1, mean)
[1] 46 47 48 49 50 51 52 53 54 55
> rm(mean) # the interpreter "knows" to only remove the vector object
> mean
function (x, ...)
UseMethod("mean")
<environment: namespace:base>
> rm(mean) # and will refuse to remove the base function
Warning message:
In rm(mean) : object 'mean' not found
Generally the interpreter can tell when a name is being intended as a
function. Certainly when () follows the name, a function will be
sought and other objects with identical names ignored.There are
exceptions to that statement and your point is very well taken, but
the main level of confusion is in the human brain rather than the R-
interpreter. There used to be more partial name matching, but my
reading of the NEWS items makes me think there is a shift away from
that facility. Other functions that people often mis-use as object
names, generally without obvious deleterious effects:
df # the density of the F distribution
c
data
sd
var
names
var.f <- function(rho) {
(1-rho)*diag(m)+rho*J%*%t(J)
}
var.f() is a complete function, except that m and J are not passed
as arguments. Instead, you rely on them being present in the
calling environment, and that is both dangerous and bad practice.
Sarah
On Fri, May 28, 2010 at 12:00 PM, li li <hannah.hlx at gmail.com> wrote:
I am not sure about "overwrite mean() with data". My purpose was to generate random numbers that are from a multivariate normal distribution with the mean vector. For the var.f function, since I already specify m and J, so the only variable is really rho, so I wrote it as a function of rho only. Could you be a little more specific? Thanks a lot again. 2010/5/28 Sarah Goslee <sarah.goslee at gmail.com>
There are a bunch of problems in your code: you overwrite mean() with data, and that could screw things up. you have a function var.f that isn't passed all the arguments it needs. est.4 is defined several times, each overwriting the previous. First you need to clean up these sorts of problems since they can lead to all kinds of bizarre results. Then, if you are still getting unexpected results, please send the list a minimal example so that we can take a look. Sarah
-- Sarah Goslee http://www.functionaldiversity.org
______________________________________________ R-help at r-project.org mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code.
David Winsemius, MD West Hartford, CT