【问题标题】:standard deviation on dataframe does not work数据框的标准偏差不起作用
【发布时间】:2014-06-05 10:42:42
【问题描述】:

我在计算标准偏差时遇到了一个意外 [至少对我来说] 错误。 想法 [*] 是将所有缺失值转换为 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 在行动中,罗伯特·卡巴科夫

【问题讨论】:

    标签: r


    【解决方案1】:

    data.frames 上的sd 自 R-3.0.0 起已失效:

    > ## 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)

    【讨论】:

    • 谢谢约书亚。这些是非常重要的功能,它破坏了我拥有的一些代码。 :-(。
    • @Henk:是的,当时它给不少 CRAN 包造成了问题。
    • @Henk 如果您不想检查旧代码并对其进行更改,您可以轻松定义自己的 mean.data.framesd.data.frame 函数。
    • 有没有其他人注意到使用sapply(x, sd) 会使代码运行慢得多?有没有比这种方法更快的替代方法?
    • @Reilstein:与什么相比要慢得多?您的评论确实应该是一个新问题,但请确保您创建了一个 reproducible example 并包含一些基准,以表明与其他方法相比它更慢。
    猜你喜欢
    • 2023-04-10
    • 1970-01-01
    • 2020-03-28
    • 2021-10-16
    • 2023-03-25
    • 2021-10-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多