按r分组和缩放/归一化r中的列 [英] group by and scale/normalize a column in r

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

问题描述

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

I have a dataframe 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

我不知道在R中是如何分组和申请。所以对于每个商店(分组),我想要归一化/缩放两列(sum_sales和temperature)。

What I can't figure out in R is how to group by and apply. So for each store (grouped), 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))
 }

我正在使用dply包,似乎无法弄清楚将该功能分组并应用于列。我试过这样的东西,并得到一个错误:

I'm using the dply package and can't seem to figure out how to group by and apply that function to a column. I tried something like this and get an error:

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

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

Any suggestions/help would be greatly appreciated. Thanks.

推荐答案

问题是你使用错误的dplyr动词。总结将为每个变量创建一个结果。你想要的是突变mutate更改变量并返回与原始长度相同的结果。请参阅 http://cran.rstudio.com/web/packages/dplyr/vignettes/introduction.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/introduction.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)

注意:Store变量在您的数据和所需结果之间是不同的。我假设@jlhoward得到了正确的数据。

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

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

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