[R] how to use apply with a function created by ourselfs...?

Peter Dalgaard BSA p.dalgaard at biostat.ku.dk
Mon Apr 21 11:27:48 CEST 2003


"ANA KOZOMARA" <magnolia at absolutok.net> writes:

> ..hey thanks for the answer, both of you...
> but :-(, I don't seem to have an answer to my problem...
> I tried with what u suggested, but it doesn't work yet...
> so I will precise it...
> I have a data frame...
> and I would like to apply the function "prediction" which acts on two
> vectors
> prediction(linear,ind),
> to my data frame,I mean to all the rows of my data frame...
> something like a function "Map" in Mathematica...
> Shortly, I want to apply function "prediction" to a list of arguments, not
> to a single argument...
> I hope now it is more clear...
> Thanks for the answers once more,
> best regards,
> ana

It depends on your prediction function. The best thing is to arrange
that it vectorizes over its arguments, as Spencer Graves suggested.
Then it's just 

prediction(df[,1],df[,2])

or, if you want something that works for more than two rows,

do.call("prediction", df) 

if your prediction() does not vectorize (i.e. a and b has to be
scalars), you can do two things:

pr.row <- function(row) do.call("prediction",row)
apply(df, 1, pr.row)

or create a vectorized prediction(), as in 

pr.vec <- function(a,b)
   sapply(seq(along=a),function(i)prediction(a[i],b[i]))

-- 
   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



More information about the R-help mailing list