File: select.Rmd

package info (click to toggle)
r-cran-dplyr 1.1.4-4
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 4,292 kB
  • sloc: cpp: 1,403; sh: 17; makefile: 7
file content (73 lines) | stat: -rw-r--r-- 1,563 bytes parent folder | download
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
```{r, include=FALSE}
# So the second library() call doesn't show messages
library(tidyverse)
```

Here we show the usage for the basic selection operators. See the
specific help pages to learn about helpers like [starts_with()].

The selection language can be used in functions like
`dplyr::select()` or `tidyr::pivot_longer()`. Let's first attach
the tidyverse:

```{r}
library(tidyverse)

# For better printing
iris <- as_tibble(iris)
```

Select variables by name:

```{r}
starwars %>% select(height)

iris %>% pivot_longer(Sepal.Length)
```

Select multiple variables by separating them with commas. Note how
the order of columns is determined by the order of inputs:

```{r}
starwars %>% select(homeworld, height, mass)
```

Functions like `tidyr::pivot_longer()` don't take variables with
dots. In this case use `c()` to select multiple variables:

```{r}
iris %>% pivot_longer(c(Sepal.Length, Petal.Length))
```

## Operators:

The `:` operator selects a range of consecutive variables:

```{r}
starwars %>% select(name:mass)
```

The `!` operator negates a selection:

```{r}
starwars %>% select(!(name:mass))

iris %>% select(!c(Sepal.Length, Petal.Length))

iris %>% select(!ends_with("Width"))
```

`&` and `|` take the intersection or the union of two selections:

```{r}
iris %>% select(starts_with("Petal") & ends_with("Width"))

iris %>% select(starts_with("Petal") | ends_with("Width"))
```

To take the difference between two selections, combine the `&` and
`!` operators:

```{r}
iris %>% select(starts_with("Petal") & !ends_with("Width"))
```