【问题标题】:Min-max normalization in R, setting groups of min and max based on another columnR中的最小值-最大值归一化,基于另一列设置最小值和最大值组
【发布时间】:2020-07-07 08:49:36
【问题描述】:

使用 R,我正在尝试对列进行最小-最大规范化,但我不需要使用所有列值的最小值和最大值,而是需要按由另一列确定的组来设置最小值和最大值。

请看这个例子:

x <- c(0, 0.5, 1, 2.5, 0.2, 0.3, 0.5, 0,0,0.1, 0.7)
y <- c(1, 1, 1, 1, 2, 2, 2, 3, 3, 3, 3)

df <- data.frame (x, y)

df

对于 y=1,min(x) = 0,max(x) = 2.5。 对于 y=2,min(x) = 0.2,max(x) = 0.5,以此类推。

基于这个分组的最小值和最大值,执行标准化。

我为 Python 找到了一个类似的问题,但对我没有多大帮助: Normalize a column of dataframe using min max normalization based on groupby of another column

【问题讨论】:

    标签: r normalization


    【解决方案1】:
    library(tidyverse)
    
    df %>%
      group_by(y) %>%
      mutate(xnorm = (x - min(x)) / (max(x) - min(x))) %>%
      ungroup()
    

    输出:

    # A tibble: 11 x 3
           x     y xnorm
       <dbl> <dbl> <dbl>
     1   0       1 0    
     2   0.5     1 0.2  
     3   1       1 0.4  
     4   2.5     1 1    
     5   0.2     2 0    
     6   0.3     2 0.333
     7   0.5     2 1    
     8   0       3 0    
     9   0       3 0    
    10   0.1     3 0.143
    11   0.7     3 1 
    

    或者,在mutate() 语句中,您可以输入xnorm = scales::rescale(x)

    【讨论】:

      【解决方案2】:

      你可以使用函数聚合

      aggregate(x, list(y), min)
        Group.1   x
      1       1 0.0
      2       2 0.2
      3       3 0.0
      aggregate(x, list(y), max)
        Group.1   x
      1       1 2.5
      2       2 0.5
      3       3 0.7
      
      # You can create your own function like this
      myFun <- function (u) {
          c(min(u), mean(u), max(u))
      } 
      # and pass myFun to aggregate
      aggregate(x, list(y), myFun)
        Group.1       x.1       x.2       x.3
      1       1 0.0000000 1.0000000 2.5000000
      2       2 0.2000000 0.3333333 0.5000000
      3       3 0.0000000 0.2000000 0.7000000
      
      # alternative is "by" different output format
      by(x, list(y), myFun)
      

      【讨论】:

        【解决方案3】:

        我不确定你是否需要类似下面的东西

        dfout <- within(df,xnorm <- ave(x,y,FUN = function(v) (v-min(v))/diff(range(v))))
        

        这样

        > dfout
             x y     xnorm
        1  0.0 1 0.0000000
        2  0.5 1 0.2000000
        3  1.0 1 0.4000000
        4  2.5 1 1.0000000
        5  0.2 2 0.0000000
        6  0.3 2 0.3333333
        7  0.5 2 1.0000000
        8  0.0 3 0.0000000
        9  0.0 3 0.0000000
        10 0.1 3 0.1428571
        11 0.7 3 1.0000000
        

        【讨论】:

          猜你喜欢
          • 2020-01-12
          • 2023-02-07
          • 2015-01-09
          • 1970-01-01
          • 2018-08-25
          • 1970-01-01
          • 1970-01-01
          • 2013-05-06
          • 1970-01-01
          相关资源
          最近更新 更多