Skip to content
Prev 140107 / 398506 Next

Geting names of variables

I wanted to create a list with the names of variables and their
values. So I wrote the following function.

add.to.list.names.vars.1 <- function(lnv, vnv) {
  i <- 1
  while (i < length(vnv)) {
    z <- as.character(eval(substitute(quote(vnv[i+1])))[[2]][[i + 2]])
    lnv[[vnv[i]]] <- list(Name = z, Value = vnv[i+1])
    i <- i + 2
  }

  lnv
}

It works, but it is very cumbersome. I wonder if there is a smarter
way to do it. Here is an example:
$`First Trade Position`
$`First Trade Position`$Name
[1] "x1"

$`First Trade Position`$Value
[1] "3"


$`Second Trade Position`
$`Second Trade Position`$Name
[1] "x2"

$`Second Trade Position`$Value
[1] "5"


$`P&L`
$`P&L`$Name
[1] "y"

$`P&L`$Value
[1] "-34.5"