Explain how to access list elements in R?

I want to know how list elements are accessed in R? Do I need vector only for that?

Create a list containing a vector, a list and a matrix.

list_data <- list(c("Feb","Mar","Apr")) list("white",13.4)), matrix(c(3,9,5,1,-2,8), nrow = 2)

For Example: Give names to the elements in the list:

`Names(list_data) <- c(“1 st  Quarter”, “A Matrix”, “A Inner list”)`

Access the first element of the list:


Access the third element. As it also a list, all its elements will print:


By using the name of the element access the list elements:

`Print(list_data$A Matrix)`

It will produced the following result after executing the above code:

$”1 st  Quarter” [1] “Feb”, "Mar”, "Apr” $A_Inner_list $A_Inner_list[[1]] [1] “White” $A_Inner_list[[2]] [1] 13.4 $ “A Matrix” [1] [1]   [2]   [3] [1]     3     5    -2 [2]     9     1     8

Lists are objects common in most programming languages; however, object specifications and subsetting may be unique to the language at hand. This is especially the case with R. I won’t cover the details on the difference between R and other languages, but let’s dive into some examples of how to subset a list.

Using the example list:
> my_list <- list(1:5)
List of 1
$ : int [1:5] 1 2 3 4 5

Use str(my_list) to view the structure of a list.

> my_list[1]
[1] 1 2 3 4 5

> typeof(my_list[1])
[1] "list"

This gives you the list at index 1, which is still a list object; not too helpful here if you want the content of the list. But if you have a list of say five lists, this will return the first list of your five lists.

> my_list[[1]]
[1] 1 2 3 4 5

[[ will extract the contents of the first list. The result will be an integer vector in this case.
[1] "integer"

So far we have subsetted lists by indexes. We can also subset lists by names:
> my_list <- list(numbers = 1:5)
> my_list["numbers"]
[1] 1 2 3 4 5

More details at the R for Data Science.