统计计算 R语言

统计计算 R语言

#8.R函数的编写+有效位数的保留
var1 = function(x)
{
n = length(x)
meanx = signif(mean(x), 6)
sumx = signif(sum(x^2), 6)
s2 = signif((sumx-n*meanx^2)/(n-1), 6)
return(s2)
}

var2 = function(x)
{
n = length(x)
meanx = signif(mean(x), 6)
sumx = 0
for (i in 1:n){
sumx = sumx + (x[i]-meanx)^2
}
s2 = signif(sumx/(n-1),6)
return(s2)
}

x = c(249,254,243,268,253,269,287,241,273,306,303,280,260,256,
278,344,304,283,310)
var1 = var1(x)
var2 = var2(x)
print(var1)
print(var2)

统计计算 R语言
#各种分布+做直方图
#?distribution
#标准正态分布

x = rnorm(10, mean = 0, sd = 1)
hist(x, freq = F)

x = rnorm(20, mean = 0, sd = 1)
hist(x, freq = F)

x = rnorm(30, mean = 0, sd = 1)
hist(x, freq = F)

x = rnorm(50, mean = 0, sd = 1)
hist(x, freq = F)

x = rnorm(100, mean = 0, sd = 1)
hist(x, freq = F)

#对数正态分布
x = rlnorm(10)
hist(x, freq = F)

x = rlnorm(20)
hist(x, freq = F)

x = rlnorm(30)
hist(x, freq = F)

x = rlnorm(50)
hist(x, freq = F)

x = rlnorm(100)
hist(x, freq = F)

#柯西分布
x = rcauchy(10, location = 0, scale = 1)
hist(x, freq = F)

x = rcauchy(20, location = 0, scale = 1)
hist(x, freq = F)

x = rcauchy(30, location = 0, scale = 1)
hist(x, freq = F)

x = rcauchy(50, location = 0, scale = 1)
hist(x, freq = F)

x = rcauchy(100, location = 0, scale = 1)
hist(x, freq = F)

第二章:
统计计算 R语言
#2.
#(1)
x = c(1, 2)
x_1 = sample(x, 100, replace = T, prob = c(1/3, 2/3))
n_1 = 0
for (i in x_1){
if (i == 1){
n_1 = n_1 + 1
}
}
library(‘scales’)
prob_1 <- percent(n_1/100)
print(prob_1)

#(2)
x_2 = sample(x, 1000, replace = T, prob = c(1/3, 2/3))
n_2 = 0
for (i in x_2){
if (i == 1){
n_2 = n_2 + 1
}
}
prob_2 <- percent(n_2/1000)
print(prob_2)

#(3)
x_3 = sample(x, 10000, replace = T, prob = c(1/3, 2/3))
n_3 = 0
for (i in x_3){
if (i == 1){
n_3 = n_3 + 1
}
}
prob_3 <- percent(n_3/10000,scale = 100) #默认为100
print(prob_3)

①R语言中用sample(x,size = n,prob = p,replace = TRUE)可以生成样本量为n的有限个值的离散型随机变量随机数,其中x是变量可取值集合,向量p是每个值对应的概率。
②R语言调包求百分数:https://blog.csdn.net/weixin_46111814/article/details/105371942

#11.
用变换法生成随机数:https://www.math.pku.edu.cn/teachers/lidf/docs/statcomp/html/_statcompbook/rng-nonuni.html#rng-nonuni-trans

上一篇:2020-11-27


下一篇:np.dot()计算两个变量的乘积