第 3 章 函数
介绍R中的函数编写知识。
library(ggplot2)
library(dplyr)
##
## 载入程辑包:'dplyr'
## The following objects are masked from 'package:stats':
##
## filter, lag
## The following objects are masked from 'package:base':
##
## intersect, setdiff, setequal, union
library(tidyr)
library(modelr)
library(lubridate)
##
## 载入程辑包:'lubridate'
## The following objects are masked from 'package:base':
##
## date, intersect, setdiff, union
library(pastecs)
##
## 载入程辑包:'pastecs'
## The following object is masked from 'package:tidyr':
##
## extract
## The following objects are masked from 'package:dplyr':
##
## first, last
3.1 概述
当需要对同一代码复制超过3次时,最好的办法就是写成函数
3.2 将下公式写为函数
\[Var(x)=\frac{1}{n-1}\sum_{i=1}^n(x_i-\bar{x})^2\] 偏度分布公式:
\[Skew(x)=\frac{\frac{1}{n-2}(\sum_{i=1}^n(x_i-\bar{x})^3)}{Var(x)^{3/2}}\]
练习题解答
#方差
= rnorm(100,10,2)
x
<- function(x){
Var = length(!is.na(x))
n = sum((x - mean(x, na.rm = T))^2)
sum /(n-1)
sum
}
<- function(x){
Skew = length(!is.na(x))
n = sum((x - mean(x, na.rm = T))^3)
sum /(Var(x)^(3/2)*(n-2))
sum
}
Skew(x)
## [1] 0.2423189
hist(x)
stat.desc(x, norm = T)
## nbr.val nbr.null nbr.na min max range
## 100.0000000 0.0000000 0.0000000 5.2317462 16.2631395 11.0313933
## sum median mean SE.mean CI.mean.0.95 var
## 1011.4877182 10.1067112 10.1148772 0.1987801 0.3944227 3.9513509
## std.dev coef.var skewness skew.2SE kurtosis kurt.2SE
## 1.9878005 0.1965225 0.2374725 0.4919064 0.8388284 0.8768281
## normtest.W normtest.p
## 0.9789541 0.1101551