在 R 中实现每个行业的单位缩放

Implement unit scaling per industry in R

我正在使用单位缩放方法创建新功能。这是数据,

Recieve = c(237, 1781, NA, 3710, 2099)
Sales = c(2509, 25616, NaN, 19224, 6569)
Industry = c("ABC", "ABC", "ABC",  "CDE", "CDE")
data = data.frame(Recieve, Sales, Industry, stringsAsFactors = FALSE)
> data
  Recieve Sales Industry
1     237  2509      ABC
2    1781 25616      ABC
3      NA   NaN      ABC
4    3710 19224      CDE
5    2099  6569      CDE

我想通过应用单位长度缩放公式来创建 Recieve_new、Sales_new 等新特征。公式是,

unitLength = x / sqrt(sum(x^2))

例如,对于 Recieve = 237 和 industry = "ABC" 中的条目,单位长度应计算如下,

unitLength = 237 / sqrt((237^2) + (1781^2))
unitLength = 237 / sqrt(56169 + 3171961)
unitLength = 237 / sqrt(3228130)
unitLength = 237 / 1796.69975232
unitLength = 0.13190851709

计算应该只包括有限的数​​据,我们可以在计算时排除无限的数据。 我想使用 R 实现这种方法。预期的输出是这样的。

  Recieve Sales Industry Recive_new  Sales_new
1     237  2509      ABC  0.1319085 0.09748012
2    1781 25616      ABC  0.9912619 0.99523747
3      NA   NaN      ABC         NA         NA
4    3710 19224      CDE  0.8703574 0.94627897
5    2099  6569      CDE  0.4924205 0.32335136

谁能帮我解决这个问题?

一个tidyverse解决方案:

data %>% 
  group_by(Industry) %>% 
  mutate(across(c(Recieve, Sales), 
                ~ .x / sqrt(sum(.x^2 + lead(.x)^2, na.rm = T)), 
                .names = "{.col}_new"))

  Recieve Sales Industry Recieve_new Sales_new
    <dbl> <dbl> <chr>          <dbl>     <dbl>
1     237  2509 ABC            0.132    0.0975
2    1781 25616 ABC            0.991    0.995 
3      NA   NaN ABC           NA      NaN     
4    3710 19224 CDE            0.870    0.946 
5    2099  6569 CDE            0.492    0.323