6

I need to create named lists dynamically in R as follows.

Suppose there is an array of names.

name_arr<-c("a","b")

And that there is an array of values.

value_arr<-c(1,2,3,4,5,6)

What I want to do is something like this:

list(name_arr[1]=value_arr[1:3])

But R throws an error when I try to do this. Any suggestions as to how to get around this problem?

nb1
  • 125
  • 1
  • 3
  • 11

3 Answers3

9

you can use [[...]] to assign values to keys given by strings:

my.list <- list()
my.list[[name_arr[1]]] <- value_arr[1:3]
pavel
  • 360
  • 1
  • 8
6

You could use setNames. Examples:

setNames(list(value_arr[1:3]), name_arr[1])
#$a
#[1] 1 2 3

setNames(list(value_arr[1:3], value_arr[4:6]), name_arr)
#$a
#[1] 1 2 3
#
#$b
#[1] 4 5 6

Or without setNames:

mylist <- list(value_arr[1:3])
names(mylist) <- name_arr[1]
mylist
#$a
#[1] 1 2 3

mylist <- list(value_arr[1:3], value_arr[4:6])
names(mylist) <- name_arr
mylist
#$a
#[1] 1 2 3
#
#$b
#[1] 4 5 6
talat
  • 68,970
  • 21
  • 126
  • 157
0

Your code will throw a error. Because in list(A = B), A must be a name instead of an object.

You could convert a object to a name by function eval. Here is the example.

eval(parse(text = sprintf('list(%s = value_arr[1:3])',name_arr[1])))
BooksE
  • 69
  • 1
  • 3
  • 2
    The `eval(parse(` daemon: http://stackoverflow.com/questions/13649979/what-specifically-are-the-dangers-of-evalparse –  Jan 27 '16 at 10:37