make a nested list in r

To make a nested list in R, you can simply create a list within a list. Here's an example:

main.r
# create a nested list
my_list <- list(
  item1 = list(
    subitem1 = "apple",
    subitem2 = "banana"
  ),
  item2 = list(
    subitem1 = "cat",
    subitem2 = "dog"
  )
)

# print the nested list
print(my_list)
214 chars
15 lines

This will create a list my_list that contains two items, each of which is a list with two subitems. You can access items and subitems using double brackets, like this:

main.r
# access the first item
print(my_list[[1]])

# access the subitem1 of the first item
print(my_list[[1]]$subitem1)

# access the second subitem of the second item
print(my_list[[2]][[2]])
187 chars
9 lines

This will print out the appropriate items and subitems within the nested list.

related categories

gistlibby LogSnag