Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically creating named list in R

Tags:

list

r

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?

like image 267
nb1 Avatar asked Dec 24 '22 09:12

nb1


2 Answers

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

my.list <- list()
my.list[[name_arr[1]]] <- value_arr[1:3]
like image 81
pavel Avatar answered Jan 09 '23 01:01

pavel


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
like image 23
talat Avatar answered Jan 09 '23 03:01

talat