-
Notifications
You must be signed in to change notification settings - Fork 2
/
R07_lists.qmd
83 lines (49 loc) · 1.2 KB
/
R07_lists.qmd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
# Lists
- stores arbitrary content (string, numeric, vectors...)
- created with `list()`, entries separated by `,`
```{r}
number = 6
l = list(5, number, "Gardenia", c(1,5))
l
```
## Some generic functions with lists
```{r}
length(l)
summary(l)
```
## Subsetting Lists
There are multiple ways to subset a list (i.e. get a specific or multiple entries).
Subsetting with `[ ]` returns a list.
```{r}
l[1]
class(l[1])
# We can select multiple entries by using a vector
l[c(1,3)]
```
More commonly you don't want a list, but the content that is stored in the list.
For this you use double square brackets `[[ ]]`.
```{r}
#| error: true
l[[2]]
class(l[[2]])
# Selecting multiple entries like this is not possible
l[[c(1,2)]]
```
## Named entries
Lists become even more useful when we start to name list entries.
Our created list does not have names (we declared no names in the list creation).
```{r}
names(l)
names(l) = c("a", "b", "c", "d")
l
```
Calling the list now also shows the entry names (after the `$`).
We can use the names now to select specific entries.
```{r}
# single brackets: return list
l[c("c", "a")]
# double brackets: return value
l[["b"]]
# or use the dollar sign $
l$b
```