[R] Geting names of variables

Fernando Saldanha fsaldan1 at gmail.com
Sat Mar 22 17:12:29 CET 2008


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:

> my.list <- list()
> x1 <- 3
> x2 <- 5
> y <- -34.5
> my.list <- add.to.list.names.vars.1(my.list, c("First Trade Position", x1, "Second Trade Position", x2, "P&L", y))
> my.list
$`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"



More information about the R-help mailing list