calculate the z score in r

To calculate the z score in R, we need to first find the mean and standard deviation of the variable of interest. Then, we can calculate the z score by subtracting the mean from the observed value and dividing by the standard deviation. Here is an example code:

# generate some simulated data from a normal distribution 
set.seed(123)
x <- rnorm(100, mean = 50, sd = 10)

# calculate the mean and standard deviation
mean_x <- mean(x)
sd_x <- sd(x)

# calculate the z score for a specific observation (e.g. 55)
obs <- 55
z_score <- (obs - mean_x) / sd_x
z_score
299 chars
13 lines

In this example, we generated 100 random values from a normal distribution with mean 50 and standard deviation 10. Then, we calculated the mean and standard deviation of the sample. Finally, we calculated the z score for an observation of 55 using the formula and printed the result (which should be 0.5).

gistlibby LogSnag