vitor
vitor

Reputation: 1250

naming lists of lists

I have a list of a list of the structure:

[[1]]
[[1]][[1]]
vector a

[[1]][[2]]
vector b

[[1]][[3]]
vector c

[[1]][[4]]
vector d

I would like to rename it like:

[["main name"]]
[["subname 1"]][[1]]
vector a
[["subname 1"]][[2]]
vector b

[["subname 2"]][[1]]
vector c
[["subname 2"]][[2]]
vector d

I don't know if that's possible to do or if I need a different data structure. Please, I'd like some advice on that.

Upvotes: 1

Views: 243

Answers (2)

rwinkel2000
rwinkel2000

Reputation: 136

myList <- list( list('vector a', 'vector b', 'vector c', 'vector d') )
names(myList) <- c('main name')
names(myList)

[1] "main name"

names(myList[['main name']]) <- c('subname 1', 'subname 2', 'subname 3', 'subname 4')

names(myList[['main name']]) 

[1] "subname 1" "subname 2" "subname 3" "subname 4"

myList[['main name']][['submname 1']] #What am I doing wrong here?
NULL

 myList[[1]][[1]]
[1] "vector a"

 myList['main name']
$`main name`
$`main name`$`subname 1`
[1] "vector a"

$`main name`$`subname 2`
[1] "vector b"

$`main name`$`subname 3`
[1] "vector c"

$`main name`$`subname 4`
[1] "vector d"

Upvotes: 0

mathematical.coffee
mathematical.coffee

Reputation: 56905

You can use names to assign and get names in lists (see ?names).

For example if I make a list of lists similar to yours (I notice that the structure of the first list in your example doesn't equal the structure of the second list - your second list appears to be nested three levels deep whereas the first is nested two levels deep):

myList <- list( list('vector a', 'vector b', 'vector c', 'vector d') )
# > myList
# [[1]]
# [[1]][[1]]
# [1] "vector a"
# 
# [[1]][[2]]
# [1] "vector b"
# 
# [[1]][[3]]
# [1] "vector c"
# 
# [[1]][[4]]
# [1] "vector d"

I can assign list names to the top level with

names(myList) <- c('main name')

This allows me to get myList[[1]] as myList[['main name']]. I can now assign list names to the myList[['main name']] like so:

names(myList[['main name']]) <- c('subname 1', 'subname 2', 'subname 3', 'subname 4')

Now if you do myList[['main name']][['submname 1']] you'll get "vector a".

Note - I recommend you don't use spaces in your names, because then you can't use syntactic sugar myList$column_name.

For example (this list has a structure more like your second one in your question to give you another example):

myList <- list( list('a', 'b'), list('c', 'd') )
names(myList) <- c('subname_1', 'subname_2')
myList$subname_1
# list('a', 'b')
# we can do list names one level deeper too if you like
names(myList$subname_1) <- c('a', 'b')
myList$subname_1$a
# 'a'

Also, it is possible to assign the names upon list construction instead of afterwards:

myList <- list( subname_1=list(a='a', b='b'), subname_2=list(c='c', d='d') )

Upvotes: 4

Related Questions