 # Explain how to access list elements in R?

Explain how to access list elements in R?
0

#1

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

#3

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

``````list_data &lt;- 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:

```````print(list_data)`
``````

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

```````Print(list_data)`
``````

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”  “Feb”, "Mar”, "Apr” \$A_Inner_list \$A_Inner_list[]  “White” \$A_Inner_list[]  13.4 \$ “A Matrix”              3     5    -2      9     1     8
``````

#4

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.

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

`> typeof(my_list)`
` "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 2 3 4 5`

`[[` will extract the contents of the first list. The result will be an integer vector in this case.
`typeof(my_list[])`
` "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"]`
`\$numbers`
` 1 2 3 4 5`

More details at the R for Data Science.