有关RStudio的代码

时间:2018-07-29 06:08:41

标签: r

有人在这里解释两行代码吗?我所知道的是关于找到分位数。这些代码来自网站,仅供参考:

quant <- function(x) {quantile(x,probs=0:10/10)}
apply(new.df[,1:dim(new.df)[2]],2,quant)

1 个答案:

答案 0 :(得分:1)

函数quant计算作为参数传递的向量的deciles。表达式1:dim(new.df)[2]返回一个向量,该向量从1开始,并以等于列数的数字结束。 new.df[, 1:dim(new.df)[2]]选择new.df中的所有列(但是很奇怪,没有直接意义,因为它与new.df本身相同)。具有第二个自变量apply的函数2一对一地取列并调用函数quant。例如:

new.df <- structure(list(a = c(36, 12, 14, 4, 3, 8, 4, 7), b = c(6, 12, 
3, 4, 6, 4, 8, 7), c = c(36, 7, 6, 4, 9, 8, 4, 7), d = c(6, 12, 
12, 5, 4, 7, 8, 7), e = c(36, 6, 3, 6, 4, 9, 4, 7), f = c(36, 
5, 4, 6, 6, 3, 8, 7), g = c(36, 12, 12, 14, 4, 6, 4, 7), h = c(6, 
6, 3, 4, 6, 8, 4, 7)), class = "data.frame", row.names = c(NA, 
-8L))
# new.df dataframe:
#   a  b  c  d  e  f  g h
# 1 36  6 36  6 36 36 36 6
# 2 12 12  7 12  6  5 12 6
# 3 14  3  6 12  3  4 12 3
# 4  4  4  4  5  6  6 14 4
# 5  3  6  9  4  4  6  4 6
# 6  8  4  8  7  9  3  6 8
# 7  4  8  4  8  4  8  4 4
# 8  7  7  7  7  7  7  7 7
quant <- function(x) {
  quantile(x, probs = 0:10 / 10)
}

apply(new.df[, 1:dim(new.df)[2]], 2, quant)

返回结果:

        a    b    c    d    e    f    g   h
0%    3.0  3.0  4.0  4.0  3.0  3.0  4.0 3.0
10%   3.7  3.7  4.0  4.7  3.7  3.7  4.0 3.7
20%   4.0  4.0  4.8  5.4  4.0  4.4  4.8 4.0
30%   4.3  4.2  6.1  6.1  4.2  5.1  6.1 4.2
40%   6.4  5.6  6.8  6.8  5.6  5.8  6.8 5.6
50%   7.5  6.0  7.0  7.0  6.0  6.0  9.5 6.0
60%   8.8  6.2  7.2  7.2  6.2  6.2 12.0 6.0
70%  11.6  6.9  7.9  7.9  6.9  6.9 12.0 6.0
80%  13.2  7.6  8.6 10.4  8.2  7.6 13.2 6.6
90%  20.6  9.2 17.1 12.0 17.1 16.4 20.6 7.3
100% 36.0 12.0 36.0 12.0 36.0 36.0 36.0 8.0