Samit
Samit

Reputation: 87

Adding a nested List in R

I am unable to add a nested list as a component to a list using c(). Pls. consider the example:

list1 <- list(1,2)
list3 <- c(list1, "list2"=list("a",4))
list3[4]

This gives:

$`list22
[1] 4`

But there is no 4th component. As per the instruction manual I am following, we can add new component to a list by

new_list <- c(old_list, new_component) 

I have added the new component (list2) and it is the 3rd component. append() also gives the same result.

Upvotes: 1

Views: 372

Answers (1)

JohnCoene
JohnCoene

Reputation: 2261

If the comment by @Hobo Sheep is correct (a list of length 2):

list1 <- list(1,2)

list3 <- list(
    list1,
    list(
        list2 = list(
            "a", 
            3
        )
    )
)

length(list3)

If you want to use append

list3 <- append(list1, list(list2 = list("a", 3)))
str(list3)

A list in R ~= JSON, so if you are more familiar with the latter:

jsonlite::toJSON(list3, auto_unbox = TRUE, pretty = TRUE)

Upvotes: 2

Related Questions