Skip to content
Prev 311388 / 398513 Next

correct function formation in R

On 20/11/2012 12:39 PM, Omphalodes Verna wrote:
fun1 above relies on the internal implementation of the data.frame 
class.  That's really unlikely to change, but you still shouldn't rely 
on it.
This one is going to be really slow, because it does so much indexing of 
the output dataframe.

I would combine the approaches:  assign to local variables in the loop 
the way fun1 does, then construct a dataframe at the end.  That is,

output <- data.frame(ID, minimum, maximum)
return(output)

One other change:  don't initialize the local variables to NULL, 
initialize them to their final size, e.g.

ID <- character(ncol(x))
minimum <- numeric(ncol(x))
maximum <- numeric(ncol(x))

(And if the contents are as simple as in the example, you don't need the 
loop, but I assume the real case is more complicated.)

Duncan Murdoch