【问题标题】:Calculate the dependency standard deviation in R计算R中的依赖标准差
【发布时间】:2017-10-10 13:10:43
【问题描述】:

我想计算 R 中的标准差。但标准函数“sd(x)”不是我需要的函数。我正在寻找一个函数来计算 sd(x,依赖于我的数据框中的另一个变量)。这样我就可以通过依赖变量(图像)添加一个带有 sd 的新列。 像这样:

image   answer    sd
a       1         0,70
a       2         0,70
b       2         2,12
b       5         2,12

【问题讨论】:

    标签: r statistics calculated-columns standard-deviation crowdsourcing


    【解决方案1】:

    函数ave 非常适合。

    dat <- read.table(text = "
    image   answer    sd
    a       1         0,70
    a       2         0,70
    b       2         2,12
    b       5         2,12
    ", header = TRUE, dec = ",")
    
    ave(dat$answer, dat$image, FUN = sd)
    #[1] 0.7071068 0.7071068 2.1213203 2.1213203
    

    编辑。
    在与 cmets 中的 Henry 对话之后,我决定编辑答案。幸运的是,与此同时,我意识到原始数据集使用逗号作为小数点。
    因此,首先进行更改,在上面的read.table 中包含参数dec = ","
    第二个更改,以显示由ave 指令创建的列sd 的完整解决方案。

    dat2 <- dat[-3]  # start with the OP's data without the 3rd column
    dat2$sd <- ave(dat2$answer, dat2$image, FUN = sd)
    dat2
    #  image answer        sd
    #1     a      1 0.7071068
    #2     a      2 0.7071068
    #3     b      2 2.1213203
    #4     b      5 2.1213203
    

    【讨论】:

    • +1 虽然也许您可以将sd 列从输入中删除,然后使用dat$sd &lt;- ave(dat$answer, dat$image, FUN = sd) 之类的内容将计算插入表中,然后打印结果
    • @Henry 你是对的,但我使用了 OP 发布的数据示例。
    • 我曾认为这是所需的输出而不是输入。没关系
    • 感谢您的 cmets。您的解决方案非常适合我
    【解决方案2】:

    我的理解是,您需要每个图像的答案的标准差。您可以按图像对 df 进行分组,然后使用 sd,它将使用 dplyr 为每个组单独计算。

    df <- data.frame(image = c('a', 'a', 'b', 'b'),
                     answer = c(1, 2, 2, 5))
    
    library(dplyr)    
    df %>%
            group_by(image) %>%
            mutate(sd = sd(answer))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-11-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-03
      • 1970-01-01
      • 1970-01-01
      • 2015-06-17
      相关资源
      最近更新 更多