整个数据框的分位数结果

Quantile results for the entire dataframe

我有一个相当大的数据集,包含大约 100 个变量和大约 100 万次观察。数据集包含数值变量和分类变量。 我想计算所有数字变量的分位数,所以当我尝试以下操作时: quantile(dat1, c(.10, .30, .5, .75, .9, na.rm = TRUE)

我在 R 中收到一条错误消息 "non-numeric argument to binary operator"

所以有人可以为我推荐合适的代码吗?感谢您的帮助和感谢

所有数字列的分位数

# sample data with numeric and character class values 
df <- data.frame(a = 1:5, b= 1:5, c = letters[1:5])
col_numeric <- which( sapply(df, is.numeric ) )   # get numeric column indices
quantile( x = unlist( df[,  col_numeric] ), 
          c(.10, .30, .5, .75, .9),
          na.rm = TRUE )

# 10% 30% 50% 75% 90% 
#  1   2   3   4   5 

单个数字列的分位数

sapply( col_numeric, function( y ) {
  quantile( x = unlist( df[,  y ] ), 
            c(.10, .30, .5, .75, .9),
            na.rm = TRUE )
})

#       a   b
# 10% 1.4 1.4
# 30% 2.2 2.2
# 50% 3.0 3.0
# 75% 4.0 4.0
# 90% 4.6 4.6

由于您的真实数据很大,您可以使用 data.table 库来提高效率。

library('data.table')
setDT(df)[, lapply( .SD, quantile, probs = c(.10, .30, .5, .75, .9), na.rm = TRUE ), .SDcols = col_numeric ]