R: creating a named vector from variables -
inside function define bunch of scalar variables this:
a <- 10 b <- a*100 c <- + b at end of function, want return a,b,c in named vector, same names variables, minimal coding, i.e. do not want do:
c( = a, b = b, c = c ) is there language construct this? example, if return(c(a,b,c)) returns unnamed vector, not want. have hacky way of doing this:
> cbind(a,b,c)[1,] b c 10 1000 1010 is there perhaps better, less hacky, way?
here's function you, allows optionally name of values. there's not it, except trick unevaluated expression , deparse single character vector.
c2 <- function(...) { vals <- c(...) if (is.null(names(vals))) { missing_names <- rep(true, length(vals)) } else { missing_names <- names(vals) == "" } if (any(missing_names)) { names <- vapply(substitute(list(...))[-1], deparse, character(1)) names(vals)[missing_names] <- names[missing_names] } vals } <- 1 b <- 2 c <- 3 c2(a, b, d = c) # b d # 1 2 3 note it's not guaranteed produce syntactically valid names. if want that, apply make.names function names vector.
c2(mean(a,b,c)) # mean(a, b, c) # 1 also, function uses substitute, c2 more suited interactive use used within function.
Comments
Post a Comment