James Owers
James Owers

Reputation: 8345

Function argument as name of variable/array in R

I'd like to be able to create a vector with R but determine its name within the function call. In SAS I would use the macro language to perform a loop but with R, I can't find how to refer to a variable by name e.g. (Obviously this does not work but it describes what I'd like to do)

fun <- function(X, vectorName) {
    paste(vectorName) <- 1:X
}

I'd like to be able to call fun(5, v) and get a vector v = c(1,2,3,4,5) out the end.

Upvotes: 0

Views: 148

Answers (1)

Roland
Roland

Reputation: 132979

Although this is possible, it's not something you should do. A function should only have a return value, which you then can assign, e.g.:

v <- seq_len(5)

Or if you have to pass a variable name programmatically:

myname <- "w"
assign(myname, seq_len(5))

(Though I can't think of a reason why you'd need that.)

Upvotes: 2

Related Questions