-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathL28_DataFiltering_Final.Rmd
85 lines (59 loc) · 1.3 KB
/
L28_DataFiltering_Final.Rmd
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
81
82
83
84
---
title: "Data Filtering"
output:
html_document:
toc: true
toc_float: true
code_folding: hide
number_sections: true
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = T, message = F, warning = F)
```
# Packages
```{r}
library(dplyr)
library(tidyr)
library(ggplot2)
```
# Data Preparation
## Load Data
```{r}
data("diamonds")
```
```{r}
summary(diamonds)
```
## Filtering Rows
You can filter for rows with **filter()**.
You can use all comparison operators, e.g. ==, !=, <=, >=, ...
You also can check for categories with %in%.
```{r}
diamonds[2, ] # 2nd row
diamonds[c(1,3), 'cut'] # 1st, 3rd row, column 'cut'
diamonds_filt <- diamonds %>%
filter (carat >= 3) %>%
filter (cut %in% c("Ideal", "Premium"))
```
Other row-based filters are **sample_n()**
```{r}
diamonds_filt <- diamonds %>%
sample_n(100)
```
or **slice()**.
```{r}
diamonds_filt <- diamonds %>%
slice(10:20)
```
or **top_n()**.
## Filtering Columns
You can filter for columns with **select()**.
There are two ways to approach this:
1. White-List: define the columns that you want to keep
2. Black-List: define the columns that you don't want to keep
```{r}
diamonds_filt <- diamonds %>%
select(carat, cut) # white-list
diamonds_filt <- diamonds %>%
select(-carat, -cut) # black-list
```