Creating a named list

Well done, you're on a roll!

Just like on your to-do list, you want to avoid not knowing or remembering what the components of your list stand for. That is why you should give names to them:

my_list <- list(name1 = your_comp1, 
                name2 = your_comp2)

This creates a list with components that are named name1, name2, and so on. If you want to name your lists after you've created them, you can use the names() function as you did with vectors. The following commands are fully equivalent to the assignment above:

my_list <- list(your_comp1, your_comp2)
names(my_list) <- c("name1", "name2")

Instruction

# Vector with numerics from 1 up to 10 my_vector <- 1:10 # Matrix with numerics from 1 up to 9 my_matrix <- matrix(1:9, ncol = 3) # First 10 elements of the built-in data frame mtcars my_df <- mtcars[1:10,] # Adapt list() call to give the components names my_list <- list(my_vector, my_matrix, my_df) # Print out my_list # Vector with numerics from 1 up to 10 my_vector <- 1:10 # Matrix with numerics from 1 up to 9 my_matrix <- matrix(1:9, ncol = 3) # First 10 elements of the built-in data frame mtcars my_df <- mtcars[1:10,] # Adapt list() call to give the components names my_list <- list(vec = my_vector, mat = my_matrix, df = my_df) # Print out my_list my_list msg = "Do not remove or change the definiton of the variables `my_vector`, `my_matrix` or `my_df`!" test_object("my_vector", undefined_msg = msg, incorrect_msg = msg) test_object("my_matrix", undefined_msg = msg, incorrect_msg = msg) test_object("my_df", undefined_msg = msg, incorrect_msg = msg) test_object("my_list", incorrect_msg = "It looks like `my_list` does not contain the correct elements.") test_object("my_list", eq_condition = "equal", incorrect_msg = "It looks like `my_list` does not contain the correct naming for the components. Make sure you use the names `vec`, `mat` and `df`, respectively. Check out the hint if you're struggling."); test_output_contains("my_list", incorrect_msg = "Don't forget to print `my_list` to the console! Simply add `my_list` on a new line in the editor.") success_msg("Great! Not only do you know how to construct lists now, you can also name them; a skill that will prove most useful in practice. Continue to the next exercise.")

The first method of assigning names to your list components is the easiest. It starts like this:

my_list <- list(vec = my_vector)

Add the other two components in a similar fashion.

Previous: 6-3 | Creating a list

Next: 6-5 | Creating a named list (2)

Back to Main