[R] correct function formation in R
Omphalodes Verna
omphalodes.verna at yahoo.com
Tue Nov 20 18:39:54 CET 2012
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)
More information about the R-help
mailing list