forked from pjsio/ME114
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathME114_assignment1_solution.R
More file actions
89 lines (73 loc) · 2.89 KB
/
Copy pathME114_assignment1_solution.R
File metadata and controls
89 lines (73 loc) · 2.89 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
## Assignment 1 R code, R only version
## ME114, 2015
## 1. To be done on your system.
## 2.1
obj1_1 <- read.table(text = "
a b c d
1 2 4.3 Yes
3 4L 5.1 No
")
## Probably not what we were expecting , since the `a - d` were values rather than variable names.
## 2.2
obj2_1 <- read.table(text = "
a b c d
1 2 4.3 Yes
3 4L 5.1 No
", header=TRUE)
## `stringsAsFactors=TRUE` reads in the non-numeric data as type `character` rather
## than creating factors from them.
## 2.3
obj3_1 <- read.table(text = "
a b c d
1 2 4.3 Yes
3 4L 5.1 No
", header=TRUE, stringsAsFactors=FALSE)
obj3_1$b <- as.integer(obj3_1$b)
obj3_1$d <- factor(obj3_1$d)
str(obj3_1)
## 2.4
obj4_1 <- read.table(text = "
a b c d
1 2 4.3 Yes
3 4L 5.1 No
", header=TRUE, stringsAsFactors=FALSE)
tmp <- gsub("L", "", obj4_1$b)
obj4_1$b <- as.integer(tmp)
str(obj4_1)
## 2.5
obj5_1 <- data.frame(obj4_1)
str(obj5_1)
## Actually, it was already a `data.frame`.
## 3. Working with the `dplyr` package
## 3.1
require(foreign)
dail2002 <- read.dta("http://www.kenbenoit.net/files/dail2002.dta")
## 3.2
require(dplyr)
dail2002FF <- filter(dail2002, party=="ff")
summary(dail2002FF$party)
## 3.3
FFspend <- select(dail2002FF, spend_total, constituency) %>%
group_by(constituency) %>%
summarise(medspend = median(spend_total))
# Sort and plot the 42 median spending values using an index plot.
plot(sort(FFspend$medspend), ylab="Median constituency spending for FF")
# For extra credit, do the same using `aggregate` instead of dplyr.
FFspend2 <- aggregate(dail2002FF$spend_total,
list(constituency=dail2002FF$constituency),
median)
## 4. Working with the `reshape2` package
library(reshape2)
# rename votes1st
names(dail2002)[which(names(dail2002FF)=="votes1st")] <- "count1"
dail2002melted <- melt(select(dail2002, wholename, district, count1, count2:count16, m),
id.vars = c("wholename", "district", "m"),
variable.name= "count",
value.name = "votes")
# strip off the number after "count" in the count variable
dail2002melted$ncount <- as.numeric(gsub("count", "", as.character(dail2002melted$count)))
dail2002maxcount <- filter(dail2002melted, votes>0) %>%
group_by(district, m) %>%
summarise(maxcount = max(ncount))
# clear relationship between constituency size and number of counts
with(dail2002maxcount, table(m, maxcount))