数据帧的标准偏差不起作用

时间:2014-06-05 10:42:43

标签: r

在计算标准差时,我有一个意想不到的[至少对我来说]错误。 想法[*]是将所有缺失值转换为1和0否则。 然后在完成关联之前提取具有一些[但不是全部]缺失值的变量。尝试使用sd函数进行提取步骤,但它失败了[为什么?]。

library(VIM)
data(sleep) # dataset with missing values

x = as.data.frame(abs(is.na(sleep))) # converts all NA to 1, otherwise 0
y = x[which(sd(x) > 0)] # attempt to extract variables with missing values

Error in is.data.frame(x) : 
(list) object cannot be coerced to type 'double'

# convert to double    
z = as.data.frame(apply(x, 2, as.numeric))
y = z[which(sd(z) > 0)]

Error in is.data.frame(x) : 
(list) object cannot be coerced to type 'double'

[*] R in Action,Robert Kabacoff

1 个答案:

答案 0 :(得分:16)

自R-3.0.0以来,data.frames上的

sd已经不存在了:

> ## Build a db of all R news entries.
> db <- news()
> ## sd
> news(grepl("sd", Text), db=db)
Changes in version 3.0.3:

PACKAGE INSTALLATION

    o   The new field SysDataCompression in the DESCRIPTION file allows
        user control over the compression used for sysdata.rda objects in
        the lazy-load database.

Changes in version 3.0.0:

DEPRECATED AND DEFUNCT

    o   mean() for data frames and sd() for data frames and matrices are
        defunct.

改为使用sapply(x, sd)