0

我试图计算给定向量的中位数,但是当我尝试时,我不断收到错误:

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")
4

1 回答 1

7

由于您正在从 excel 中读取它,因此 R 正在查看“DIV#0”消息并认为您的数据是分类的,就好像它是说“蓝色”、“绿色”、“淡褐色”等的数据。所以当你在问median,R 认为你在问眼睛颜色的中值,这没有任何意义。

要将因子列表转换为数字:

returns.numbers <- as.numeric(as.vector(returns))
median(returns.numbers)
于 2012-11-02T23:04:31.327 回答