按组缩放/标准化列 [英] scale/normalize columns by group

查看:27
本文介绍了按组缩放/标准化列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个如下所示的数据框:

I have a data frame that looks like this:

  Store Temperature Unemployment Sum_Sales
1     1       42.31        8.106   1643691
2     1       38.51        8.106   1641957
3     1       39.93        8.106   1611968
4     1       46.63        8.106   1409728
5     1       46.50        8.106   1554807
6     1       57.79        8.106   1439542

对于每个商店",我想标准化/缩放两列(Sum_sales"和Temperature").

For each 'Store', I want to normalize/scale two columns ("Sum_sales" and "Temperature").

所需的输出:

  Store Temperature Unemployment Sum_Sales
1     1       1.000        8.106   1.00000
2     1       0.000        8.106   0.94533
3     1       0.374        8.106   0.00000
4     2       0.012        8.106   0.00000
5     2       0.000        8.106   1.00000
6     2       1.000        8.106   0.20550

这是我创建的规范化函数:

Here is the normalizing function that I created:

 normalit<-function(m){
   (m - min(m))/(max(m)-min(m))
 }

我尝试过的:

df2 <- df %.%
  group_by('Store') %.%
  summarise(Temperature = normalit(Temperature), Sum_Sales = normalit(Sum_Sales)))

任何建议/帮助将不胜感激.谢谢.

Any suggestions/help would be greatly appreciated. Thanks.

推荐答案

问题是您使用了错误的 dplyr 动词.Summarize 将为每个变量的每个组创建一个结果.你想要的是变异.Mutate 更改变量并返回与原始长度相同的结果.请参阅 http://cran.rstudio.com/web/packages/dplyr/小插图/dplyr.html.下面是使用 dplyr 的两种方法:

The issue is that you are using the wrong dplyr verb. Summarize will create one result per group per variable. What you want is mutate. Mutate changes variables and returns a result of the same length as the original. See http://cran.rstudio.com/web/packages/dplyr/vignettes/dplyr.html. Below two approaches using dplyr:

df %>%
    group_by(Store) %>%
    mutate(Temperature = normalit(Temperature), Sum_Sales = normalit(Sum_Sales))

df %>%
    group_by(Store) %>%
    mutate_each(funs(normalit), Temperature, Sum_Sales)

注意:存储变量在您的数据和所需结果之间是不同的.我以为@jlhoward 得到了正确的数据.

Note: The Store variable is different between your data and desired result. I assumed that @jlhoward got the right data.

这篇关于按组缩放/标准化列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆