z score by group in r

To z score by group in R, you can use the group_by() function from the dplyr package to group your data by a specific column, and then use the mutate() function to calculate the z-score for each value within that group. Here's an example:

main.r
library(dplyr)

# create a sample data frame
df <- data.frame(group = rep(c("A", "B"), each = 5),
                 value = c(3, 2, 5, 6, 4, 8, 9, 6, 10, 7))

# group by "group" column and calculate z-score for "value" column
df <- df %>% 
  group_by(group) %>% 
  mutate(z_score = scale(value))

# view the updated data frame
df
329 chars
14 lines

In this example, we've created a sample data frame with two columns (group and value). We then used the group_by() function to group the data by the group column, and then used the mutate() function to calculate the z-score for each value within each group. The resulting data frame includes a new column called z_score that contains the z-score for each value.

related categories

gistlibby LogSnag