-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWorking with Data.R
More file actions
95 lines (73 loc) · 1.73 KB
/
Working with Data.R
File metadata and controls
95 lines (73 loc) · 1.73 KB
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
# Working with Data
# Set the working directory
setwd("/home/emu/R Projects/Data Science with R/")
# Read a tab-delimited data file
cars <- read.table(
file = "Cars.txt",
header = TRUE,
sep = "\t",
quote = "\"")
# Peek at the data
head(cars,5)
# remove faulty data with 'NA'
cars <- na.omit(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
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
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)