forked from DoubleD1994/R_Tutorial
-
Notifications
You must be signed in to change notification settings - Fork 0
/
WorkingWithData.R
97 lines (76 loc) · 1.7 KB
/
WorkingWithData.R
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
85
86
87
88
89
90
91
92
93
94
95
96
97
# Working with Data
#Set Working directory
setwd("/Users/daviddryburgh/Documents/R_Programming")
# Read a CSV data file
cars <- read.csv("Cars.csv")
# Peek at the data
head(cars)
# Load the dplyr library
library(dplyr)
# Select a subset of columns
temp <- select(
.data = cars,
Transmission,
Cylinders,
Fuel.Economy
)
# Inspect the results
head(temp)
# Filter a subset of rows
temp <- filter(
.data = temp,
Transmission == "Automatic"
)
# Inspect the results
head(temp)
# Compute a new column
temp <- mutate(
.data = temp,
Consumption = Fuel.Economy * 0.425
)
# Inspect the results
head(temp)
# Group by a column
temp <- group_by(
.data = temp,
Cylinders
)
# Inspect the results
head(temp)
# Aggregate based on groups, this showing the average consumption of cars
# based on the number of cyliders
temp <- summarize(
.data = temp,
Avg.Consumption = mean(Consumption)
)
# Inspect the results
head(temp)
# Arrange the rows in descending order
temp <- arrange(
.data = temp,
desc(Avg.Consumption)
)
# Inspect the results
head(temp)
# Convert to data frame
efficiency <- as.data.frame(temp)
# Inspect the results
print(efficiency)
# Chain methods together. %>% is a piping sequence to join methods together
# and write cleaner R code
efficiency <- cars %>%
select(Fuel.Economy, Cylinders, Transmission) %>%
filter(Transmission == "Automatic") %>%
mutate(Consumption = Fuel.Economy * 0.425) %>%
group_by(Cylinders) %>%
summarize(Avg.Consumption = mean(Consumption)) %>%
arrange(desc(Avg.Consumption)) %>%
as.data.frame()
# Inspect the results
print(efficiency)
# Save the results to a CSV file
write.csv(
x = efficiency,
file = "Fuel Efficiency.csv",
row.names = FALSE
)