【问题标题】:Use scale() function to standard deviation without centering使用 scale() 函数来标准偏差而不居中
【发布时间】:2018-06-27 00:23:30
【问题描述】:

在我正在分析的数据集中,我选择了一些变量,我想缩放到 1 个标准差,但不是中心。我在下面的示例中使用scale()function 进行了尝试。

require(tidyverse)

set.seed(1)
df <- data.frame(replicate(10, sample(0:1000, 1000, rep = TRUE)))
scaled_vars <- df %>%
    select(X1 : X6) %>%
    map(~scale(., center = F)

但是,通过阅读scale()文档,如果center = F 则缩放到均方根,而不是标准差。文档指出,要在不居中的情况下缩放到标准偏差,请使用代码:

scale(x, center = FALSE, scale = apply(x, 2, sd, na.rm = T))

但是,我似乎无法让该代码在我的 map 函数中工作。

map(~scale(., center = F, scale = apply(., 2, sd, na.rm = T)

错误消息指出找不到对象“x”。如何调整我的代码以实现我的目标?谢谢。

【问题讨论】:

    标签: r


    【解决方案1】:

    map 循环遍历每一列。 scale 函数中的 scale 参数将 sd 用于该特定列。基于apply 的方法是当我们有多个列时。

    out <- df %>% 
             select(X1:X6) %>% 
             map_df(~ scale(.x, center = FALSE, scale = sd(.x, na.rm = TRUE)))
    

    -检查 OP 的基本 R 代码生成的输出

    out1 <- scale(df[1:6], center = FALSE, 
             scale = apply(df[1:6], 2, sd, na.rm = TRUE))
    
    all.equal(as.matrix(out), out1, check.attributes = FALSE)
    #[1] TRUE
    

    【讨论】:

    • 感谢您如此迅速地提供解决方案。我注意到您的解决方案提供的答案与设置 scale = Tcenter = T 相同
    • @Paul 我得到了与您展示的base R 版本类似的输出
    • 我可以看到您的解决方案产生了与base R 相同的输出。我认为在统计数据方面一定有一些我没有掌握的东西。我需要去阅读更多内容。再次感谢。
    • @Paul 如果你查看?scale中的描述The value of ‘center’ determines how column centering is performed. If ‘center’ is a numeric vector with length equal to the number of columns of ‘x’, then each column of ‘x’ has the corresponding value from ‘center’ subtracted from it. If ‘center’ is ‘TRUE’ then centering is done by subtracting the column means (omitting ‘NA’s) of ‘x’ from their corresponding columns, and if ‘center’ is ‘FALSE’, no centering is done.
    • @Paul 因此,通过仅给出 TRUE 或 FALSE,它正在为每个列进行居中 m1 &lt;- matrix(1:30, 5, 6); d1 &lt;- as.data.frame(m1); scale(d1, center = FALSE, scale = TRUE) 并检查 scale(d1, center = TRUE, scale = TRUE)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-16
    • 1970-01-01
    • 1970-01-01
    • 2014-05-09
    • 1970-01-01
    相关资源
    最近更新 更多