-
Notifications
You must be signed in to change notification settings - Fork 463
/
Copy path06-factors.R
117 lines (88 loc) · 2.71 KB
/
06-factors.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
library(tidyverse)
library(forcats)
day_levels <- c("Lun", "Mar", "Mie", "Jue", "Vie", "Sab", "Dom")
x1 <- c("Vie", "Lun", "Mar", "Dom")
sort(x1)
y1 <- factor(x1, levels = day_levels)
sort(y1)
x2 <- c("Vim", "Lun", "Mar", "Dom")
y2 <- factor(x2, levels = day_levels)
y2
y2 <- parse_factor(x2, levels = day_levels)
factor(x1)
f1 <- factor(x1, levels = unique(x1))
f2 <- x1 %>% factor() %>% fct_inorder()
levels(f2)
gss_cat %>% View()
gss_cat %>% count(marital)
gss_cat %>% ggplot(aes(marital)) +
geom_bar()
gss_cat %>% ggplot(aes(race)) +
geom_bar() +
scale_x_discrete(drop = FALSE)
religion_summary <- gss_cat %>%
group_by(relig) %>%
summarise(
age = mean(age, na.rm = TRUE),
tvhours = mean(tvhours, na.rm = TRUE),
n = n()
)
religion_summary %>% View()
ggplot(religion_summary, aes(tvhours, relig)) + geom_point()
ggplot(religion_summary, aes(tvhours, fct_reorder(relig, tvhours))) +
geom_point()
religion_summary %>%
mutate(relig = fct_reorder(relig, tvhours)) %>%
ggplot(aes(tvhours, relig)) +
geom_point()
gss_cat %>%
group_by(rincome) %>%
summarise(
age = mean(age, na.rm = TRUE),
tvhours = mean(tvhours, na.rm = TRUE),
n = n()
) %>%
#mutate(rincome = fct_reorder(rincome, age)) %>%
mutate(rincome = fct_relevel(rincome, "Not applicable")) %>%
ggplot(aes(age, rincome)) +
geom_point()
by_age <- gss_cat %>%
filter(!is.na(age)) %>%
group_by(age, marital) %>%
count()
ggplot(by_age, aes(age, n, color = marital)) +
geom_line(na.rm = TRUE)
ggplot(by_age, aes(age, n, color = fct_reorder2(marital, age, n)))+
geom_line(na.rm = TRUE)+
labs(color = "Marital")
gss_cat %>%
mutate(marital = marital %>% fct_infreq() %>% fct_rev()) %>%
ggplot(aes(marital)) +
geom_bar()
gss_cat %>% count(partyid)
gss_cat %>%
mutate(partyid = fct_recode(partyid,
"Republican, strong" = "Strong republican",
"Republican, weak" = "Not str republican",
"Independent, near rep" = "Ind,near rep",
"Independent, near dem" = "Ind,near dem",
"Democrat, weak" = "Not str democrat",
"Democrat, strong" = "Strong democrat",
"Other" = "No answer",
"Other" = "Don't know",
"Other" = "Other party"
)
) %>% count(partyid)
gss_cat %>%
mutate(partyid = fct_collapse(partyid,
other = c("No answer", "Don't know", "Other party"),
rep = c("Strong republican", "Not str republican"),
ind = c("Ind,near rep", "Independent", "Ind,near dem"),
dem = c("Not str democrat", "Strong democrat")
)
) %>%
count(partyid)
gss_cat %>%
mutate(relig = fct_lump(relig, n = 5)) %>%
count(relig, sort = TRUE) %>%
print(n = 3)