appending to a list with dynamic names

You can use setNames to set the names on the fly:

a <- list(n1 = "hi", n2 = "hello")
c(a,setNames(list("hola"),paste("another","name",sep="_")))

Result:

$n1
[1] "hi"

$n2
[1] "hello"

$another_name
[1] "hola"

You could just use indexing with double brackets. Either of the following methods should work.

a <- list(n1 = "hi", n2 = "hello")
val <- "another name"
a[[val]] <- "hola"
a
#$n1
#[1] "hi"
#
#$n2
#[1] "hello"
#
#$`another name`
#[1] "hola"

 a[[paste("blah", "ok", sep = "_")]] <- "hey"
 a
#$n1
#[1] "hi"
#
#$n2
#[1] "hello"
#
#$`another name`
#[1] "hola"
#
#$blah_ok
#[1] "hey"

Tags:

List

R

Names

Append