library(tidyverse)
## ── Attaching packages ─────────────────────────────────────────────────────────────── tidyverse 1.2.1 ──
## ✔ ggplot2 3.2.1 ✔ purrr 0.3.2
## ✔ tibble 2.1.3 ✔ dplyr 0.8.3
## ✔ tidyr 0.8.3 ✔ stringr 1.4.0
## ✔ readr 1.3.1 ✔ forcats 0.4.0
## ── Conflicts ────────────────────────────────────────────────────────────────── tidyverse_conflicts() ──
## ✖ dplyr::filter() masks stats::filter()
## ✖ dplyr::lag() masks stats::lag()
n <- 200
x1 <- rnorm(n, mean = 5, sd = 1)
x2 <- rnorm(n, mean = 10, sd = 1)
x3 <- rnorm(n, mean = 15, sd = 1)
d <- tibble(xs = c(x1, x2, x3), cl = rep(letters[1:3], each = n))
ggplot(d, aes(x = xs, fill = cl)) +
geom_histogram(bins = 50)

km <- kmeans(d$xs, centers = 3)
d$km <- as.character(km$cluster)
ggplot(d, aes(x = xs, fill = km)) +
geom_histogram(bins = 50)

wss <- sapply(1:10, function(k ) kmeans(d$xs, nstart = 20, centers = k)$tot.withinss)
qplot(wss, 1:10)

library(pastecs)
##
## Attaching package: 'pastecs'
## The following objects are masked from 'package:dplyr':
##
## first, last
## The following object is masked from 'package:tidyr':
##
## extract
dens <- density(d$xs)
ts_y <- ts(dens$y)
tp <- turnpoints(ts_y)
plot(dens)
points(dens$x[tp$tppos], dens$y[tp$tppos], col = 'red')
