r如何计算非数字数据的标准偏差和方差?

How does r calculate the standard deviation and variance for non numeric data?

我的任务是计算调查中四个变量的标准差和方差。其中两个变量是数值型的,而另外两个则不是。我运行下面的代码:

sapply(vclms[1:4], var)

Vclms 是包含变量的数据框,第 1 至 4 列包括所有上述变量(包括数值变量和其他变量)。我预计它会为非数值变量的方差提供错误,但却得到以下信息:

> sapply(vclms[1:4], var)
     grosswk        spend     hhldsize          sex 
8.383855e+04 4.744934e+04 1.288881e+00 2.434469e-01 
Warning messages:
1: In FUN(X[[i]], ...) :
  Calling var(x) on a factor x is deprecated and will become an error.
  Use something like 'all(duplicated(x)[-1L])' to test for a constant vector.
2: In FUN(X[[i]], ...) :
  Calling var(x) on a factor x is deprecated and will become an error.
  Use something like 'all(duplicated(x)[-1L])' to test for a constant vector.

我不知道你是否可以考虑两个非数字变量(hhldsize 和 sex)的答案是否正确,但我想知道它是如何得出答案的?

因为警告消息表明这是应该避免的事情,但是如果你有一个因素

x<-factor(c("a","b","c","c","d","b","a","b","a","a"))

该因素中的每个值都由一个整数表示。

as.numeric(x)
# [1] 1 2 3 3 4 2 1 2 1 1

数字由一个因素的 levels() 决定。每个级别都分配了一个从 1 开始的整数。

levels(x)
# [1] "a" "b" "c" "d"

因此 a=1b=2、等等

当你做 var(x) 时,你实际上是在做 var(as.numeric(x))。请注意,这些数值可能对您的实际数据没有意义。

var(x)
# [1] 1.111111  (plus warning)
var(as.numeric(x))
# [1] 1.111111
var(c(1, 2, 3, 3, 4, 2, 1, 2, 1, 1))
# [1] 1.111111