Kingindanord
Kingindanord

Reputation: 2036

Convert Variables to characters in R

I want to take the names of the variables in a and results as in b

a <- list(EURUSD,USDJPY,CADJPY)

b <- c("EURUSD", "USDJPY", "CADJPY")

How can I do it instead of writing it manually?

Upvotes: 1

Views: 163

Answers (3)

G. Grothendieck
G. Grothendieck

Reputation: 269396

We cannot create a and then determine the variable names that went into it by inspecting a itself since at the point a is created the variable names are lost; however, we can create a function namify to which is passed not a but list(EURUSD, USDJPY, CADJPY). In that case the function could parse the input expression and also evaluate it.

namify <- function(x) {
    setNames(x, sapply(substitute(x)[-1], deparse))
}

# test it
EURUSD <- USDJPY <- CADJPY <- 1
L <- namify(list(EURUSD, USDJPY, CADJPY))

giving this named list:

> L
$EURUSD
[1] 1

$USDJPY
[1] 1

$CADJPY
[1] 1

names(L) and unname(L) would be the names and unnamed list respectively.

Note that the preferred way to do all this really is to start with a named list in the first place. For example, supposing that each variable is stored in a csv file in current directory:

csvFiles <- Sys.glob("*.csv")
L <- Map(read.csv, csvFiles)
names(L) <- sub("[.]csv$", "", names(L))   # remove .csv from names

Upvotes: 0

akrun
akrun

Reputation: 886938

We can use substitute

f1 <- function(...) {
 v1 <- sapply(as.list(substitute(list(...)))[-1], deparse)
 v2 <- unlist(strsplit(v1, "list|[(), ]"))
 v2[nzchar(v2)]
 }

f1(EURUSD)
#[1] "EURUSD"

f1(list(EURUSD, USDJPY))
#[1] "EURUSD" "USDJPY"

f1(list(EURUSD,USDJPY,CADJPY))
#[1] "EURUSD" "USDJPY" "CADJPY"

data

EURUSD <- 1:10
USDJPY <- 11:20
CADJPY <- 21:30

Upvotes: 1

Dmitrii I.
Dmitrii I.

Reputation: 716

First, R evaluates lazily, but when you assigned the list to the variable a the expression list(EURUSD, USDJPY, CADJPY) got evaluated. Unless the three objects are named and have exactly same names, it is not possible to get their names.

What you could try is parse the output of ls(): look for all 6 character all caps names in your namespace.

Example:

EURUSD <- runif(10)
USDJPY <- runif(10)
CADJPY <- runif(10)

blablabla <- 'unused variable'

currency_pairs <- ls(pattern='^[A-Z]{6}$')
print(currency_pairs)
[1] "CADJPY" "EURUSD" "USDJPY"

Upvotes: 3

Related Questions