Daan11
Daan11

Reputation: 67

Extract variable names from list or vector in R

Assuming:

aa = c('A','B','C')
bb = c('D','E','F')
list1 = list(aa,bb)
vect1 = c(aa,bb)

Is there a way to extract the variable names as strings ('aa', 'bb') from either list1 or vect1? Is this information being stored in lists and vectors? If not, what would be the appropriate format?

Thanks in advance!

Upvotes: 4

Views: 14957

Answers (3)

shofla
shofla

Reputation: 53

You can also get there by adapting vect1 using cbind:

vect1 = cbind(aa,bb)
colnames(vect1)

Upvotes: 1

jack jay
jack jay

Reputation: 2503

For the situation what you have done the answer is no. But if you are ready to do some changes in your code then you can easily get it,

list1 <- list( aa = aa, bb = bb)

Now you can easily access the string version of names of variables from which list is formed,

names(list1)

Upvotes: 6

Ben Bolker
Ben Bolker

Reputation: 226077

aa = c('A','B','C')
bb = c('D','E','F')
list1 = list(aa,bb)
vect1 = c(aa,bb)

The short answer is no. If you look at the results of dput(list1) and dput(vect1), you'll see that these objects don't contain that information any more:

list(c("A", "B", "C"), c("D", "E", "F"))
c("A", "B", "C", "D", "E", "F")

There is one way you can get this information, which is when the expression has been passed to a function:

 f <- function(x) {
    d <- substitute(x)
    n <- sapply(d[-1],deparse)
    return(n)
 }
 f(c(aa,bb))
 ## [1] "aa" "bb"

However, it would be good to have more context about what you want to do.

Upvotes: 4

Related Questions