Brandon Bertelsen
Brandon Bertelsen

Reputation: 44648

Get the names of list variables when provided as function parameters

Lets say I have a function that accepts variables that are always part of a list.

myfun <- function(x$name,y$name) { 
 # stuff 
} 

What I'd like to do is get the names used.

alist <- list(Hello=1,Goodbye=2)

myfun(alist$Hello, alist$Goodbye) { 
 # I want to be able to work with the characters "Hello" and "Goodby" in here
}

So, within my function, how would I get the characters "Hello" and "Goodbye". Given alist$Hello and alist$Goodbye

Upvotes: 2

Views: 168

Answers (3)

Arun
Arun

Reputation: 118799

I'd create the function with a list argument:

myfun <- function(l) {
    print(names(alist))
}
myfun(alist)
# [1] "Hello"   "Goodbye"

Upvotes: 3

Matthew Lundberg
Matthew Lundberg

Reputation: 42659

Something like this, perhaps:

myfun <- function(x) { print(substitute(x))}
myfun(iris$Sepal.Length)
## iris$Sepal.Length

Upvotes: 6

Blue Magister
Blue Magister

Reputation: 13363

I recall that plot.default does this with deparse(substitute(:

a <- list(a="hello",b=c(1,2,3))
f <- function(x,y) { print(deparse(substitute(x))); print(deparse(substitute(y))) }
f(a$a,a$b)
#[1] "a$a"
#[1] "a$b"

Upvotes: 9

Related Questions