Tpellirn
Tpellirn

Reputation: 796

How to change and assign the name of a list?

If I have this list here:

list1 <- list(2, "hello", c(3, 5, 4))

and I have this:

ff <- "Bar"

I want to change the name of the list from "list1" to "Bar" via ff.

Upvotes: 0

Views: 931

Answers (2)

Konrad Rudolph
Konrad Rudolph

Reputation: 545588

You’d use (nested) lists for this purpose. At its most rudimentary, this could look as follows:

results = list()

for (var in c('foo', 'bar', 'baz')) {
    results[[var]] = list1
}

This will generate a new list with three items named foo, bar and baz, each of which is a copy of list1. To access the individual values, you’d use e.g. result$foo, or result[['foo']] (the latter is necessary if you have the value’s name stored in a variable, since access via $ doesn’t work with variables on the right-hand side).

You can adapt this for your specific purposes. Do note that, in most cases, the loop would be replaced by a more appropriate function. For instance, the above would be done better using replicate:

result = setNames(replicate(3L, list1, simplify = FALSE), c('foo', 'bar', 'baz'))

Either way, don’t dynamically create variables. It’s never an appropriate solution for this kind of problem. Instead, it makes the code more complex and harder to understand. To keep code as simple as possible, variables should only be created explicitly in code (i.e. by assignments or as function parameters, etc.).

Upvotes: 2

CIAndrews
CIAndrews

Reputation: 1043

Note that it's in general a very bad idea to change variable names dynamically. For all intents and purposes, you should consider variable names to be static, and tied to the code you write. (as commented by @Konrad Rudolph). See for example https://www.techrepublic.com/blog/it-security/never-use-dynamic-variable-names/

If you really want to use this, you can use assign(ff,list1). This creates a variable called Bar and contains the list

Upvotes: 0

Related Questions