简体   繁体   中英

Create a variable with a value that is the name of another variable in R

In R, how can you create a variable that it's value is the name of another variable?

For example: I have the vector groupers :

groupers <- c("Epinephelus.costae", "Epinephelus.marginatus",
              "Mycteroperca.rubra", "Serranus.cabrilla", "Serranus.scriba")

and I'd like to create an output that would be like that:

grp_name <- "groupers"

This seems like a simple operation but I don't know how the name of a vector is stored and therefore I can't figure out how to call it.

Cheers

If you want to take an object name and convert it to a character string, use this:

grp_name <- deparse(substitute(groupers))
grp_name
# [1] "groupers"

I would imagine you do not only have a single vector but several. So you could assemble them in a dataframe and store the names of the dataframe columns calling the function names() :

groupers <- c("Epinephelus.costae", "Epinephelus.marginatus",
              "Mycteroperca.rubra", "Serranus.cabrilla", "Serranus.scriba")
group2 <- c("Epinephelus", "Epinephelus",
              "Mycteroperca", "Serranus", "Serranus")

Assemble the vectors in a dataframe:

df <- data.frame(groupers, group2)

Store the names in a new vector:

groupnames <- names(df); groupnames
[1] "groupers" "group2"

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