Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding elements to a list in R (in nested lists)

Tags:

list

r

I have a nested list l3 as:

l1<- as.list(c(1,2,3,4,5))
l1

l2<- as.list(c(6,7,8,9,10))
l2

l3<- list(l1,l2)
l3

l3 shows as:

> l3
[[1]]
[[1]][[1]]
[1] 1

[[1]][[2]]
[1] 2

[[1]][[3]]
[1] 3

[[1]][[4]]
[1] 4

[[1]][[5]]
[1] 5


[[2]]
[[2]][[1]]
[1] 6

[[2]][[2]]
[1] 7

[[2]][[3]]
[1] 8

[[2]][[4]]
[1] 9

[[2]][[5]]
[1] 10

I need to add a third list l4 to l3 such that l3 becomes:

[[1]][[1]]
    [1] 1

to

[[2]][[5]]
    [1] 10


[[3]][[1]]
    [1] 30

[[3]][[2]]
    [1] 32

[[3]][[3]]
    [1] 33

[[3]][[4]]
    [1] 34

[[3]][[5]]
    [1] 35

where l4 was:

l4<- as.list(c(31,32,33,34,35))

how do I accomplish it? I've tried (c), list, even explicitly put the arguments and got an out of bounds error. What can I use to get this done?

like image 968
jackStinger Avatar asked Dec 27 '12 11:12

jackStinger


People also ask

How do I add a element to a nested list?

To add new values to the end of the nested list, use append() method. When you want to insert an item at a specific position in a nested list, use insert() method. You can merge one list into another by using extend() method. If you know the index of the item you want, you can use pop() method.

How do I add an item to an existing list in R?

To add or append an element to the list in R use append() function. This function takes 3 parameters input list, the string or list you wanted to append, and position. The list. append() function from the rlist package can also use to append one list with another in R.

Can you have a vector of lists in R?

Almost all data in R is stored in a vector, or even a vector of vectors. A list is a recursive vector: a vector that can contain another vector or list in each of its elements. Lists are one of the most flexible data structures in R.


2 Answers

It works with append and list:

append(l3, list(l4))

The result:

> str(append(l3, list(l4)))
List of 3
 $ :List of 5
  ..$ : num 1
  ..$ : num 2
  ..$ : num 3
  ..$ : num 4
  ..$ : num 5
 $ :List of 5
  ..$ : num 6
  ..$ : num 7
  ..$ : num 8
  ..$ : num 9
  ..$ : num 10
 $ :List of 5
  ..$ : num 31
  ..$ : num 32
  ..$ : num 33
  ..$ : num 34
  ..$ : num 35
like image 54
Sven Hohenstein Avatar answered Nov 15 '22 10:11

Sven Hohenstein


I don't know what you have tried with c, but it works

c(l3,list(l4))

PS: append is a wrapper of c to insert in a specific index, (see after argument )

like image 24
agstudy Avatar answered Nov 15 '22 08:11

agstudy