Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to rescale/normalize data between -1 and 1 in R using groups

Tags:

r

dplyr

I have data like this:

Name Data
A      5
A      6
A     -1
A     -3
B      6
B      2
B     -1
B      9

I want to normalize the data so the values are between -1 and 1. I also want to do group it by name.

Here is what I am trying:

library(dplyr)
library(scales)

df2 <- df %>% 
  group_by(name) %>%  
  rescale(Data,to=c(-1,1))

I get this error:

Error in UseMethod("rescale") : no applicable method for 'rescale' applied to an object of class "c('grouped_df', 'tbl_df', 'tbl', 'data.frame')"

like image 382
AJ Jebelli Avatar asked Feb 01 '26 09:02

AJ Jebelli


2 Answers

It should be within mutate

library(dplyr)
library(scales)
df %>% 
    group_by(Name) %>%
    mutate(Data = rescale(Data, to = c(-1, 1))) %>%
    ungroup

-output

# A tibble: 8 x 2
  Name    Data
  <chr>  <dbl>
1 A      0.778
2 A      1    
3 A     -0.556
4 A     -1    
5 B      0.4  
6 B     -0.4  
7 B     -1    
8 B      1    

data

df <- structure(list(Name = c("A", "A", "A", "A", "B", "B", "B", "B"
), Data = c(5L, 6L, -1L, -3L, 6L, 2L, -1L, 9L)), 
class = "data.frame", row.names = c(NA, 
-8L))
like image 167
akrun Avatar answered Feb 03 '26 23:02

akrun


A base R option

transform(
  df,
  Data_normalize = ave(Data,
    Name,
    FUN = function(x) (x - min(x)) / diff(range(x)) * 2 - 1
  )
)

gives

  Name Data Data_normalize
1    A    5      0.7777778
2    A    6      1.0000000
3    A   -1     -0.5555556
4    A   -3     -1.0000000
5    B    6      0.4000000
6    B    2     -0.4000000
7    B   -1     -1.0000000
8    B    9      1.0000000
like image 35
ThomasIsCoding Avatar answered Feb 03 '26 23:02

ThomasIsCoding



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!