r0bt
r0bt

Reputation: 591

R iterate to create list of lists/vectors without appending

Edit I think I solved it with Map()

mylist <- Map(list, colors = colors, items = items)
names(mylist) <- codes

Forgive my lack of experience here and apologies if I fudge some terminology. Correction and guidance appreciated.

I want to create a list of vectors so I may access each element using the $ operator.

If I create something like this:

mylist <- list()
mylist$r1$color <- 'red'
mylist$r1$items <- c('red1','red2','red3')

Then the correct structure is created and I am able to access mylist$r1, mylist$r1$items, mylist$r1$items[2], etc.

List of 1
 $ r1:List of 2
  ..$ color: chr "red"
  ..$ items: chr [1:3] "red1" "red2" "red3"

However, I have multiple lists and so need to avoid hard coding and so would like to iterate to create a list of multiple elements all with the same structure though perhaps different length sub-elements. Something like:

codes <- c('r1','b1','g1')
colours <- c('red','blue','green')
items<- list(c('red1','red2','red3'),c('blu1','blu2','blu3', 'blu4'),c(1,2,3,4,5,6,7,8))

Given this data, I would like to iterate to create a structure like this:

List of 3
 $ r1:List of 2
  ..$ color: chr "red"
  ..$ items: chr [1:3] "red1" "red2" "red3"

 $ b1:List of 2
  ..$ color: chr "blue"
  ..$ items: chr [1:4] "blu1" "blu2" "blu3" "blu4"

 $ g1:List of 2
  ..$ color: chr "green"
  ..$ items: int[1:8] 1 2 3 4 5 6 7 8 

Enabling me to call, for example:

> mylist$b1
$color
[1] "blue"
$items
[1] "blue1" "blue2" "blue3" "blue4"

> mylist$g1$items[3]
[1] 3

I have attempted to construct multiple for loops but can't seem to separate the lists into the correct structure within mylist. The codes, colors and items lists just get appended as is.

I'd appreciate some pointers in achieving my aims please.

Upvotes: 1

Views: 25

Answers (1)

akrun
akrun

Reputation: 887501

We can use Map to create a list from corresponding elements of colours and 'items', then set the names of the output list with codes

mylist2 <- setNames(Map(list, color = colours, items=items), codes)

-checking

> str(mylist2)
List of 3
 $ r1:List of 2
  ..$ color: chr "red"
  ..$ items: chr [1:3] "red1" "red2" "red3"
 $ b1:List of 2
  ..$ color: chr "blue"
  ..$ items: chr [1:4] "blu1" "blu2" "blu3" "blu4"
 $ g1:List of 2
  ..$ color: chr "green"
  ..$ items: num [1:8] 1 2 3 4 5 6 7 8

Upvotes: 1

Related Questions