R中的中位数需要数字数据

时间:2012-11-02 22:41:55

标签: r vector statistics median

我试图计算给定矢量的中位数,但是当我尝试时,我一直在收到错误:

median(returns)
Error in median.default(returns) : need numeric data

> returns
 [1] 0.001262733  -0.005048584 -0.009160197 0.010411955  -0.00542421 
 [6] -0.010982649 -0.005807832 0.000863131  -0.00210823  0.000117543 
[11] 0.001319904  0.005307534  0.005246006  0.008469327  0.006006664 
[16] -0.001411188 -0.011446652 0.002669714  0.003896259  -0.003060607
[21] 0.006306116  0.000895311  -0.006235211 -0.000856819 -0.00056599 
[26] 0.00808345   0.00038652   -0.004070623 0.008398158  -0.005976036
[31] 0.011270873  0.007959499  0.003776885  -0.000591663 0.001163452 
[36] 0.005759682  0.000678132  0.000609123  -0.000735042
40 Levels: -0.00056599 -0.000591663 -0.000735042 -0.000856819 ... 0.011270873

dput(returns)
structure(c(25L, 9L, 14L, 39L, 10L, 15L, 11L, 22L, 6L, 18L, 26L, 
31L, 30L, 38L, 33L, 5L, 16L, 27L, 29L, 7L, 34L, 23L, 13L, 4L, 
1L, 36L, 19L, 8L, 37L, 12L, 40L, 35L, 28L, 2L, 24L, 32L, 21L, 
20L, 3L), .Label = c("-0.00056599", "-0.000591663", "-0.000735042", 
"-0.000856819", "-0.001411188", "-0.00210823", "-0.003060607", 
"-0.004070623", "-0.005048584", "-0.00542421", "-0.005807832", 
"-0.005976036", "-0.006235211", "-0.009160197", "-0.010982649", 
"-0.011446652", "#DIV/0!", "0.000117543", "0.00038652", "0.000609123", 
"0.000678132", "0.000863131", "0.000895311", "0.001163452", "0.001262733", 
"0.001319904", "0.002669714", "0.003776885", "0.003896259", "0.005246006", 
"0.005307534", "0.005759682", "0.006006664", "0.006306116", "0.007959499", 
"0.00808345", "0.008398158", "0.008469327", "0.010411955", "0.011270873"
), class = "factor")

1 个答案:

答案 0 :(得分:5)

由于您正在从excel中读取它,因此R正在查看“DIV#0”消息并将您的数据视为分类,就好像它是“蓝色”,“绿色”,“淡褐色”等数据一样所以当你要求median时,R会认为你要求的是眼睛颜色的中位数,这是没有意义的。

将要素列表转换为数字:

returns.numbers <- as.numeric(as.vector(returns))
median(returns.numbers)