I am trying to normalize a dataframe by group in R. The reason why I am doing this is because I want to run a regression equation on each group for the revenue and want to obtain the slope. Because the data is not normally distributed, I wanted to normalize the dataset by group to get a better read on the trend.
The function I am using to normalize the dataset is as follows:
normalize <- function(x){
return((x-min(x)) / max(x)-min(x))
}
I know there is another already built function in R called scale
.
My datafame looks like this:
df
Date Partner Revenue
1 2017-03-01 A 33121
2 2017-03-02 A 32758
3 2017-03-03 A 34675
4 2017-03-04 A 32407
5 2017-03-05 A 30851
6 2017-03-06 A 33248
7 2017-03-07 A 34288
8 2017-03-08 A 33820
9 2017-03-09 A 36021
10 2017-03-10 A 38757
11 2017-03-11 A 41149
12 2017-03-12 A 36203
13 2017-03-13 A 41167
14 2017-03-14 A 50237
15 2017-03-15 A 48463
16 2017-03-01 B 2123
17 2017-03-02 B 1684
18 2017-03-03 B 1246
19 2017-03-04 B 1099
20 2017-03-05 B 2314
21 2017-03-06 B 1565
22 2017-03-07 B 1610
23 2017-03-08 B 1749
24 2017-03-09 B 1917
25 2017-03-10 B 1784
26 2017-03-11 B 1662
27 2017-03-12 B 1748
28 2017-03-13 B 1452
29 2017-03-14 B 880
30 2017-03-15 B 591
Using the normalize function I tried this route, but the NEWREV
numbers are not between 0 and 1. Rather they range from -30,000 to -590.
scaled_data <-
df %>%
group_by(`Partner`) %>%
mutate(NEWREV = normalize(Revenue))
How would I scale my revenue by group so that the numbers are between 0 and 1?
It looks like you are missing some parentheses in your definition of the function normalize
:
normalize <- function(x){
return((x-min(x)) / (max(x)-min(x)))
}