R Lists


Lists

List R can contain many different types of data within it. List a single and flexible data collection.

To create a list, use the list() function:


Example
# List of strings
thislist <- list("apple", "banana", "cherry")

# Print the list
thislist


Access Lists

You can access the list items by referring to its reference number, inside brackets. The first item has point 1, the second item has point 2, and so on:


Example
thislist <- list("apple", "banana", "cherry")

thislist[1]


Change Item Value

To change the value of an item, see the reference number:


Example
thislist <- list("apple", "banana", "cherry")
thislist[1] <- "blackcurrant"

# Print the updated list
thislist


List Length

To find out how many items the list has, use the length() function:


Example
thislist <- list("apple", "banana", "cherry")

length(thislist)


Check if Item Exists

To find out if something is listed, use %in% operator:


Example
thislist <- list("apple", "banana", "cherry")

"apple" %in% thislist


Add List Items

To add an item to the end of the list, use the append() function:


Example

Add "orange" to the list:

thislist <- list("apple", "banana", "cherry")

append(thislist, "orange")

To add an item to the right of a specific index, add "after = index number" to the append() function:


Example

Add "orange" to the list after "banana"(index 2):

thislist <- list("apple", "banana", "cherry")

append(thislist, "orange", after = 2)


Remove List Items

You can also delete list items. The following example creates a new, updated list without the "apple" item:


Example

Remove "apple" from the list:

thislist <- list("apple", "banana", "cherry")

newlist <- thislist[-1]

# Print the new list
newlist


Range of Indexes

You can specify a range of indicators by specifying where to start and where to end the range, using : operator:


Example

Return the second, third, fourth and fifth item:

thislist <- list("apple", "banana", "cherry", "orange", "kiwi", "melon", "mango")

(thislist)[2:5]

Note: Search will start in index 2 (included) and end in index 5 (included).

Remember that the first item has index 1.



Loop Through a List

You can access the list items by using the for loop:


Example
thislist <- list("apple", "banana", "cherry")

for (x in thislist) {
  print(x)
}


Join Two Lists

There are several ways to join, or merge, two or more columns in R.

The most common method is to use the c() function, which combines two elements together:


Example
list1 <- list("a", "b", "c")
list2 <- list(1,2,3)
list3 <- c(list1,list2)

list3