-
Notifications
You must be signed in to change notification settings - Fork 0
/
Chapter04.R
173 lines (141 loc) · 4.67 KB
/
Chapter04.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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
# Data Science with SQL Server Quick Start Guide
# Chapter 04
# Load RODBC library and read SQL Server data
library(RODBC)
con <- odbcConnect("AWDW", uid = "RUser", pwd = "Pa$$w0rd")
TM <-
sqlQuery(con,
"SELECT CustomerKey, CommuteDistance,
TotalChildren, NumberChildrenAtHome,
Gender, HouseOwnerFlag,
NumberCarsOwned, MaritalStatus,
Age, YearlyIncome, BikeBuyer,
EnglishEducation AS Education,
EnglishOccupation AS Occupation
FROM dbo.vTargetMail;")
close(con)
# View(TM)
# Basic distribution
table(TM$NumberCarsOwned)
# Attach a DF
attach(TM)
# Education is ordered by a custom order
Education = factor(Education, order = TRUE,
levels = c("Partial High School",
"High School", "Partial College",
"Bachelors", "Graduate Degree"))
# Plot
plot(Education, main = 'Education',
xlab = 'Education', ylab = 'Number of Cases',
col = "purple")
# Package descr
install.packages("descr")
library(descr)
freq(Education)
# A quick summary for Age
summary(Age)
# Details for Age
# Centers
mean(Age)
median(Age)
# Spread
min(Age)
max(Age)
range(Age)
quantile(Age, 1 / 4)
quantile(Age, 3 / 4)
IQR(Age)
var(Age)
sd(Age)
sd(Age) / mean(Age)
# Custom function for skewness and kurtosis
skewkurt <- function(p) {
avg <- mean(p)
cnt <- length(p)
stdev <- sd(p)
skew <- sum((p - avg) ^ 3 / stdev ^ 3) / cnt
kurt <- sum((p - avg) ^ 4 / stdev ^ 4) / cnt - 3
return(c(skewness = skew, kurtosis = kurt))
}
skewkurt(Age)
###########################
# More code as a bonus:-) #
###########################
# 2X2 grid graphs
# Generating a subset data frame
cols1 <- c("CustomerKey", "NumberCarsOwned", "TotalChildren")
TM1 <- TM[TM$CustomerKey < 11010, cols1]
names(TM1) <- c("CustomerKey1", "NumberCarsOwned1", "TotalChildren1")
attach(TM1)
# Generating a table from NumberCarsOwned and BikeBuyer
nofcases <- table(NumberCarsOwned, BikeBuyer)
nofcases