0

If I have a variable such as name.string <- "name", how can I use that to assign the name of a value in a list to return something like

$name
  [1] "value"

Using list(name.string = "value") returns $name.string [1] value.

And for reasons I can't seem to figure out, list(get("name.string") = "value") returns

Error: unexpected '=' in "list(get("name.string") =".

Obviously, I'm not interested in the manual solution (write "name" in the assignment) since this is being replicated for thousands of rows.

4
  • mylist <- list(name = "oldvalue"); mylist[[name.string]] <- "value" Is that what you're after? Commented Feb 19, 2014 at 21:50
  • @Frank - it's the inverse situation, where I want to create a new key with that key name. Matthew's answer gets at that. Commented Feb 19, 2014 at 22:10
  • 1
    Okay. I think mylist <- list(); mylist[[name.string]] <- "value"; mylist[[name.string2]] <- "value2" should do that. You can try it out to see, or look at help("[[") Commented Feb 19, 2014 at 22:14
  • Perfect @Frank. That's exactly what I wanted (and I feel like a dolt for not thinking of it). If you submit an answer I'll accept. Commented Feb 19, 2014 at 22:18

2 Answers 2

2

You can access and assign by number or name using double brackets:

mylist                 <- list()
name.string            <- "name"
name.string2           <- "name2"
value                  <- "hello"
value2                 <- "world"

mylist[[name.string]]  <- value
mylist[[name.string2]] <- value2

# an alternative to the previous line
# that fails to create a name:
mylist[[2]]            <- value2 

For details on this kind of assignment, see help("[[<-").

As Matthew Plourde said, this dynamically grows your list, so it might be best to preallocate, e.g., with mylist <- vector("list",2).

Sign up to request clarification or add additional context in comments.

Comments

0

You can use:

structure(list('value'), names=name.string)

or

l <- list('value')
names(l) <- name.string

or even

within(list(), assign(name.string, 'value'))

But don't use this last one.

2 Comments

Is it possible to do this recursively? Something like: my.list <- list(); my.list = c(my.list, name.string = 'value'). I've been able to do names(l) <- name.string if I knew the whole set of names, but I was hoping to learn how to do this recursively.
I suggest preallocating your list to the desired size, adding each element, and build a name vector at the same time. Then use the second method above to assign all of the names at once.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.