[R] Geting names of variables

John Kane jrkrideau at yahoo.ca
Sat Mar 22 17:23:26 CET 2008


I don't quite understand what you doing but have you
looked at ?names ?

 x1 <- 3
 x2 <- 5
 y <- -34.5
mylist <- list(x1,x2,y)
mynames <- c("First Trade  Position",  "Second Trade
Position",  "P&L")
names(mylist) <- mynames
mylist


--- Fernando Saldanha <fsaldan1 at gmail.com> wrote:

> 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"
> 
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide
> http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained,
> reproducible code.
>



More information about the R-help mailing list