[R] correct function formation in R

Rui Barradas ruipbarradas at sapo.pt
Tue Nov 20 18:52:27 CET 2012


Hello,

I believe it's a matter of personal taste. I find fun2 more readable, 
others may not agree.

Rui Barradas
Em 20-11-2012 17:39, Omphalodes Verna escreveu:
> Dear list!
>   
> I have question of 'correct function formation'. Which function (fun1 or fun2; see below) is written more correctly? Using ''structure'' as output or creating empty ''data.frame'' and then transform it as output? (fun1 and fun1 is just for illustration).
>   
> Thanks a lot, OV
>   
> code:
> input <- data.frame(x1 = rnorm(20), x2 = rnorm(20), x3 = rnorm(20))
> fun1 <- function(x) {
>      ID <- NULL; minimum <- NULL; maximum <- NULL
>      for(i in seq_along(names(x)))   {
>          ID[i]       <- names(x)[i]
>            minimum[i]  <- min(x[, names(x)[i]])
>              maximum[i]  <- max(x[, names(x)[i]])
>                                      }
>      output <- structure(list(ID, minimum, maximum), row.names = seq_along(names(x)), .Names = c("ID", "minimum", "maximum"), class = "data.frame")
>      return(output)
> }
> fun2 <- function(x) {
>      output <- data.frame(ID = character(), minimum = numeric(), maximum = numeric(), stringsAsFactors = FALSE)
>      for(i in seq_along(names(x)))   {
>          output[i, "ID"] <-names(x)[i]
>          output[i, "minimum"]  <- min(x[, names(x)[i]])
>          output[i, "maximum"]  <- max(x[, names(x)[i]])
>                                      }
>      return(output)
> }
>
> fun1(input)
> fun2(input)
>
> ______________________________________________
> 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.




More information about the R-help mailing list