简体   繁体   中英

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!

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)
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.

You can also get there by adapting vect1 using cbind :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM