1、计算向量长度:length()
> length(diag(4)) # = 16 (4 x 4)
[1] 16
> length(seq(1, 9, by = pi))
[1] 3
2、求和:sum()
sum(..., na.rm = FALSE)
> sum(1, 2, 3, 4, 5)
[1] 15
> sum(1:5, NA) # 若向量中含NA,则和为NA
[1] NA
> sum(1:5, NA, na.rm = TRUE) ## 若向量中含NA,na.rm可计算除NA外的向量之和
[1] 15
3、计算平均值:mean()
mean(x, trim = 0, na.rm = FALSE, ...)
> x <- c(0:10, 50)
> xm <- mean(x)
> c(xm, mean(x, trim = 0.10)) ## mean(x, trim = 0.10) 先把x的最大的10%的数和最小的10%的数去掉,然后剩下的数算平均
[1] 8.75 5.50
4、计算中位数:median()
median(x, na.rm = FALSE, ...)
> median(1:4)
[1] 2.5
> median(c(1:3, 100, 1000))
[1] 3
5、计算最小值:min()、计算最大值:max()
max(..., na.rm = FALSE)
min(..., na.rm = FALSE)
> max(1:10)
[1] 10
> min(1:10)
[1] 1
7、计算方差:sd()
sd(x, na.rm = FALSE)
> sd(1:2)
[1] 0.7071068
> sd(1:2) ^ 2
[1] 0.5