# Fit skewed normal distribution to data in R

The Skew-Normal Probability Distribution

#### Simulating data

`fGarch`包的`rsorm`函数来生成一个Skew Normal Distribution，`xi`为偏态参数；或者用`sn`包的`dsn`函数

``````library(sn)
library(fGarch)

# sn
data <- rsn(1000, xi=-5, omega=2, alpha=5)
# fGarch
data <- rsnorm(1000, mean = 0, sd = 1, xi = 1.5)``````

#### Parameter estimation

`sn`包为例，用`selm`函数拟合skewed distribution并绘制曲线

``````set.seed(123)
data <- rsn(1000, xi=-5, omega=2, alpha=5)
# Fit curve
fit <- selm(data ~ 1, family = "SN")
plot(fit)``````

``````> fit@param\$dp
xi      omega      alpha
0.3207890  1.0157198 -0.4102392 ``````

``````ggplot(data = data.frame(x = data), aes(x = x)) +
geom_histogram(aes(y = ..density..), colour = "black", fill = "white") +
stat_function(fun = dsn, args = c(omega = 2.02, alpha = 5.05, xi = -5.04))``````

`fGarch`包为例，用`snormFit`函数拟合skewed distribution并绘制曲线

``````set.seed(123)
data <- rsnorm(1000, mean = 0, sd = 1, xi = 1.5)
# Fit curve
snormFit(data)``````

``````> snormFit(data)\$par
mean          sd          xi
-0.01508664  1.00081242  1.61583737 ``````

`dsnorm`函数来生成密度分布

``````ggplot(data = data.frame(x = data), aes(x = x)) +
geom_histogram(aes(y = ..density..), colour = "black", fill = "white") +
stat_function(fun = dsnorm, args = c(mean = -0.015, sd = 1.00, xi = 1.61))``````

``````set.seed(123)
data <- rsnorm(1000, mean = 0, sd = 1, xi = 1.5)
fit <- selm(data ~ 1, family = "SN")
fit@param\$dp
snormFit(data)\$par

ggplot(data = data.frame(x = data), aes(x = x)) +
geom_histogram(aes(y = ..density..), colour = "black", fill = "white") +
stat_function(mapping = aes(colour = "fGarch"), size = 1.2,
fun = dsnorm, args = c(mean = as.numeric(snormFit(data)\$par["mean"]),
sd = as.numeric(snormFit(data)\$par["sd"]),
xi = as.numeric(snormFit(data)\$par["xi"]))) +
stat_function(mapping = aes(colour = "sn"), size = 1.2,
fun = dsn, args = c(omega = as.numeric(fit@param\$dp["omega"]),
alpha = as.numeric(fit@param\$dp["alpha"]),
xi = as.numeric(fit@param\$dp["xi"]))) +
scale_colour_manual(name = NULL, values = c("blue", "red"))``````