简体   繁体   中英

Integers/expressions as names for elements in lists

I am trying to understand names, lists and lists of lists in R. It would be convenient to have a way to dynamically label them like this:

> ll <- list("1" = 2)
> ll
$`1`
[1] 2

But this is not working:

> ll <- list(as.character(1) = 2)
Error: unexpected '=' in "ll <- list(as.character(1) ="

Neither is this:

> ll <- list(paste(1) = 2)
Error: unexpected '=' in "ll <- list(paste(1) ="

Why is that? Both paste() and as.character() are returning "1".

The reason is that paste(1) is a function call that evaluates to a string, not a string itself.

The The R Language Definition says this:

Each argument can be tagged (tag=expr), or just be a simple expression. 
It can also be empty or it can be one of the special tokens ‘...’, ‘..2’, etc.

A tag can be an identifier or a text string.

Thus, tags can't be expressions.

However, if you want to set names (which are just an attribute), you can do so with structure, eg

> structure(1:5, names=LETTERS[1:5])
A B C D E 
1 2 3 4 5 

Here, LETTERS[1:5] is most definitely an expression.

If your goal is simply to use integers as names (as in the question title), you can type them in with backticks or single- or double-quotes (as the OP already knows). They are converted to characters, since all names are characters in R.


I can't offer a deep technical explanation for why your later code fails beyond "the left-hand side of = is not evaluated in that context (of enumerating items in a list)". Here's one workaround:

mylist <- list()
mylist[[paste("a")]] <- 2 
mylist[[paste("b")]] <- 3
mylist[[paste("c")]] <- matrix(1:4,ncol=2)
mylist[[paste("d")]] <- mean

And here's another:

library(data.table)
tmp <- rbindlist(list( 
    list(paste("a"), list(2)), 
    list(paste("b"), list(3)),
    list(paste("c"), list(matrix(1:4,ncol=2))),
    list(paste("d"), list(mean))
))

res <- setNames(tmp$V2,tmp$V1)

identical(mylist,res) # TRUE

The drawbacks of each approach are pretty serious, I think. On the other hand, I've never found myself in need of richer naming syntax.

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