z score by group tidyverse in r

To calculate the z-score of a variable by group using the tidyverse package in R, we can use the group_by() and mutate() functions along with the scale() function.

Assuming we have a data frame called "df" with a variable "x" that we want to z-score by groups in "group_var", we can use the following code:

main.r
library(tidyverse)

df <- df %>% 
  group_by(group_var) %>% 
  mutate(x_zscore = scale(x))
91 chars
6 lines

The group_by() function groups the data by the variable specified in "group_var".

The mutate() function creates a new variable called "x_zscore" that will contain the z-scores for "x".

The scale() function calculates the z-score for each value of "x" within each group.

Note that the scale() function automatically centers the data by subtracting the mean, and scales it by dividing by the standard deviation. If you need to use a different scaling function, you can specify it as an argument to scale().

gistlibby LogSnag