make a long list in r

To make a long list in R, you can use the list() function. This function creates a list and allows you to include any number of elements within it. Here's an example of creating a list with six elements:

main.r
my_list <- list("apple", "banana", "cherry", 1, 2, 3)
54 chars
2 lines

In this example, we create a list called my_list with six elements: three strings and three integers. Note that the elements of a list in R do not have to be of the same type.

You can add elements to the list using the c() function. For instance, to add four more elements to my_list, we can use:

main.r
my_list <- c(my_list, "orange", 4, "grapefruit", 5)
52 chars
2 lines

Here, we use the c() function to combine my_list with another list of four elements. Now my_list has ten elements.

You can also access and modify elements within the list using indexing. For example, to access the third element of my_list, we can use:

main.r
my_list[[3]]
13 chars
2 lines

To modify the fourth element of my_list, we can use:

main.r
my_list[[4]] <- "kiwi"
23 chars
2 lines

In this example, we change the value of the fourth element of my_list from 1 to "kiwi".

gistlibby LogSnag