[R] Writing do and resample functions

Ben Ward benjamin.ward at bathspa.org
Tue Jan 4 11:36:25 CET 2011


Hi,

I'm trying to take a function from a workspace download provided in a 
stats textbook book, so I have it in my workspace to use all the time.

I opened the workspace and typed the names of the two functions to get 
the code that makes them up:
-------------------------------------------------------------------------------------
 > resample
function(d, size, replace=TRUE,prob=NULL,within=NULL) {
   if (!is.null(within)) return( resample.within(d, 
within,replace=replace) )
   if (is.null(dim(d))) {
      # it's just a vector
      if (missing(size)) size=length(d)
         return( d[ sample(1:length(d),size, replace=replace, prob=prob)])
   }
   else {
      if (missing(size)) size = dim(d)[1];
      inds = sample(1:(dim(d))[1], size, replace=replace, prob=prob)
      if (is.data.frame(d) | is.matrix(d)) {
         return(d[inds,]);
      } else {
         return(d[inds]);
      }
   }
}
-------------------------------------------------------------------------------------
 > do
function(n=10){
   as.repeater(n)
}
-------------------------------------------------------------------------------------
 > as.repeater
function(n=5){
   foo = list(n=n)
   class(foo) = 'repeater'
   return(foo)
}

Then I made the functions in my workspace by choosing the name (same 
name), and then "=" and then copied and pasted the function, beginning 
with function( and ending with the final }'s.

But when I try to do the following in my workspace afterwards:

samps = do(500)* coef(lm(MIC.~1+Challenge+Cleaner+Replicate, 
data=resample(ecoli)))
sd(samps)

I get an error:
Error in do(500) * coef(lm(MIC. ~ 1 + Challenge + Cleaner + Replicate,  :
non-numeric argument to binary operator.

But in the workspace that comes with that book, I get a decent output:

sd(samps)
     (Intercept)       Challenge   CleanerGarlic  ReplicateFirst 
ReplicateFourth
       3.9455401       0.7178385       1.6830641       5.4564926       
5.4320998
ReplicateSecond  ReplicateThird
       5.3895562       5.5422622

Is there anybody out there who know a lot more about programming 
functions in R than I do, that might know why this is giving me the 
error? I don't understand why one workspace would accept the model 
formula, when the other give me the non-numeric argument to binary 
vector, the only vector that's not numerical is Replicate, but I don't 
that's what the error is talking about.

Thanks,
Ben Ward.



More information about the R-help mailing list