【问题标题】:Apply function to a dataframe which utilises means of columns (~ Pareto scaling)将函数应用于利用列方式的数据框(~ Pareto scaling)
【发布时间】:2019-09-27 06:53:39
【问题描述】:

在数据框中,我想将每个值除以列值的标准差的平方根(~ Pareto Scaling)。我已从现有包中获取代码 (https://github.com/cran/RFmarkerDetector/blob/master/R/scaling.R)

paretoscale <- function(data) {
    # Here we perform centering
    x.centered <- apply(x, 2, function(x) x - mean(x))
    # Then we perform scaling on the mean-centered matrix
    x.sc <- apply(x.centered, 2, function(x) x/sqrt(sd(x)))
    x.sc <- cbind(sample_classes, x.sc)

x.centered &lt;- apply(x, 2, function(x) x - mean(x) 是不是应该像 x - mean(column where x is) 那样做?你能解释一下它是如何工作的吗?

【问题讨论】:

    标签: r dataframe apply


    【解决方案1】:

    变量名称可能有点缺乏教学意义,尤其是对于新手而言。让我们重写apply 部分,以免混淆读者。

    paretoscale <- function(data) {
        # Here we perform centering
        x.centered <- apply(x, 2, function(col) col - mean(col))
        # Then we perform scaling on the mean-centered matrix
        x.sc <- apply(x.centered, 2, function(col) col/sqrt(sd(col)))
        x.sc <- cbind(sample_classes, x.sc)
    

    apply(x, 2, function(col) col - mean(col)) 的作用是在对象x(data.frame 或矩阵)上按列运行。对于每一列,它会找到它的平均值并减去每个元素的平均值。

    下面是applyfor 循环的比较。

    xy <- data.frame(matrix(1:9, ncol = 3))
    
    apply(X = xy, MARGIN = 2, FUN = function(col) col - mean(col))
    
         X1 X2 X3
    [1,] -1 -1 -1
    [2,]  0  0  0
    [3,]  1  1  1
    
    # Create an empty object
    newxy <- xy
    newxy[] <- NA
    
    # Work column-wise
    for (i in 1:ncol(xy)) {
      col <- xy[, i]
      # Calculate mean and substract it from all elements of the column
      newxy[, i] <- col - mean(col)
    }
    newxy
    
      X1 X2 X3
    1 -1 -1 -1
    2  0  0  0
    3  1  1  1
    

    【讨论】:

    • 非常感谢!所以在 x.centered 中,第一个 'x' 指的是数据框的元素,但在 'function(x) x - mean(x)' x 实际上已经解决了整个列? (因为它是apply函数的参数?)
    猜你喜欢
    • 2020-03-23
    • 2019-06-01
    • 2021-03-20
    • 1970-01-01
    • 2020-04-24
    • 2019-05-01
    • 1970-01-01
    相关资源
    最近更新 更多