[R] Equations as arguments to functions
Peter Dalgaard BSA
p.dalgaard at biostat.ku.dk
Tue Nov 27 23:39:38 CET 2001
Michaell Taylor <pols1oh at bestweb.net> writes:
> rm(list=ls())
> load("datasets/citycodes")
> increments _ seq(5000,100000,by=5000)
> makeindex <- function(Y,eq) {
> losers _ 0; levels_0
> index _ 0; location _ 0; cutoff _0; totalapt_0; houses_0
> for (C in city[1:2]) {
> counter _ 0
> if (file.exists(paste("datasets/2000income/",C,sep=""))) {
> load(paste("datasets/2000income/",C,sep=""))
> counter _ counter+1}
> if (file.exists(paste("datasets/rents/2000",toupper(C),sep=""))) {
> load(paste("datasets/rents/2000",toupper(C),sep=""))
> counter _ counter+1}
> if (counter== 2) {
> totrent _ 0
> totrent _ rep(rent,units)
> totrent _ totrent[!is.na(totrent)]
> income2000 _ sort(income2000)
> print(C)
> print(length(income2000)) # for debugging - notice this works fine
> print(ls()) # for debugging - notice this works fine
> level _ eq # FAILURE POINT
[snip]
> makeindex(.35,eq=(income2000[.33*length(income2000)]))
...
> This smells like a "I am an idiot" sort of problem. I must be missing
> something simple.
Yes. Arguments are evaluated *in the caller environment*. If you type
base <- 2
log(base)
then you don't get log(exp(1)) even though the log function has a
local variable called base.
I assume that income2000 is defined by the load(...) constructs, and
thus are only available in the evaluation environment of the function.
If you really want to pass an expression to be evaluated internally in
the function, try
level <- eval(eq)
and call it with an explicitly quoted argument, like this
makeindex(.35,eq=quote(income2000[.33*length(income2000)]))
--
O__ ---- Peter Dalgaard Blegdamsvej 3
c/ /'_ --- Dept. of Biostatistics 2200 Cph. N
(*) \(*) -- University of Copenhagen Denmark Ph: (+45) 35327918
~~~~~~~~~~ - (p.dalgaard at biostat.ku.dk) FAX: (+45) 35327907
-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
Send "info", "help", or "[un]subscribe"
(in the "body", not the subject !) To: r-help-request at stat.math.ethz.ch
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._
More information about the R-help
mailing list