Indexing List Elements
List elements can be accessed in several ways. And just like in vectors, indexing starts at 1
.
Access by Index
Elements in a list can be accessed with either single or double brackets:
- Using single brackets (
[ ]
) returns the element as a list; - Using double brackets (
[[ ]]
) returns the value itself.
Example
123456test <- list(text = "Text", number = 42, logical = TRUE) # Extract as list test[2] # Extract as value test[[2]]
Access by Label
If a list has labels, you can extract elements using those labels. Just like with indices, you can use single brackets ([ ]
) to return a list or double brackets ([[ ]]
) to return the value. Additionally, the dollar sign ($
) provides a shorthand for accessing values.
Example
1234567test <- list(text = "Text", number = 42, logical = TRUE) # Extract as list test["text"] # Extract as value test[["text"]] test$text
Swipe to start coding
You have a list info
with course information.
You task is to:
- Extract the first element as a list.
- Output the class of this element with the
class()
function. - Extract the fourth element as a numeric type.
- Output the class of this element with the
class()
function.
Solution
Thanks for your feedback!
single
Ask AI
Ask AI
Ask anything or try one of the suggested questions to begin our chat
Can you explain the difference between single and double brackets in more detail?
What happens if I try to access an element that doesn't exist in the list?
Can you show more examples of accessing list elements by label?
Awesome!
Completion rate improved to 2.27
Indexing List Elements
Swipe to show menu
List elements can be accessed in several ways. And just like in vectors, indexing starts at 1
.
Access by Index
Elements in a list can be accessed with either single or double brackets:
- Using single brackets (
[ ]
) returns the element as a list; - Using double brackets (
[[ ]]
) returns the value itself.
Example
123456test <- list(text = "Text", number = 42, logical = TRUE) # Extract as list test[2] # Extract as value test[[2]]
Access by Label
If a list has labels, you can extract elements using those labels. Just like with indices, you can use single brackets ([ ]
) to return a list or double brackets ([[ ]]
) to return the value. Additionally, the dollar sign ($
) provides a shorthand for accessing values.
Example
1234567test <- list(text = "Text", number = 42, logical = TRUE) # Extract as list test["text"] # Extract as value test[["text"]] test$text
Swipe to start coding
You have a list info
with course information.
You task is to:
- Extract the first element as a list.
- Output the class of this element with the
class()
function. - Extract the fourth element as a numeric type.
- Output the class of this element with the
class()
function.
Solution
Thanks for your feedback!
single