2018年6月12日 星期二

R for mean, median, mode, var, sd

> x=seq(3,10,2)
> x

[1] 3 5 7 9

> mean(x)

[1] 6

> mean(x+2)

[1] 8

> mean(3*x)

[1] 18

> mean(3*x+2)

[1] 20

> x-mean(x)

[1] -3 -1 1 3

> (x-mean(x))^2

[1] 9 1 1 9

> sum((x-mean(x))^2)/length(x)

[1] 5

> ((x+2)-mean(x+2))^2

[1] 9 1 1 9

> sum(((x+2)-mean(x+2))^2)/length(x)

[1] 5

> (3*x-mean(3*x))^2

[1] 81 9 9 81

> sum(((3*x)-mean(3*x))^2)/length(x)

[1] 45

> sum(((3*x+2)-mean(3*x+2))^2)/length(x)

[1] 45

> x=c(1,2,3,3,3,4,5,6,8)
> x

[1] 1 2 3 3 3 4 5 6 8

> median(x)

[1] 3

getmode <- function(v) {
uniqv <- unique(v)
uniqv[which.max(tabulate(match(v, uniqv)))]
}
> getmode(x)

[1] 3

> x=c(1,4,2,rep(3,3),4,5,6,8)
> x

[1] 1 4 2 3 3 3 4 5 6 8

> sort(x)

[1] 1 2 3 3 3 4 4 5 6 8

> length(x)

[1] 10

> x_sort=sort(x)
> x_sort

[1] 1 2 3 3 3 4 4 5 6 8

> sum(x_sort[5]:x_sort[6])/2

[1] 3.5

> median(x)

[1] 3.5

> getmode(x)

[1] 3