Function that calculates the mean-centered values of a particular variable for each subject.

calc.mcent(x, id, data, na.rm=TRUE)

## Arguments

x

argument to specify the variable.

id

argument to specify a subject id variable.

data

optional data frame that contains the variables specified above.

na.rm

logical indicating whether missing values should be removed before computing the means (default is TRUE).

## Details

The function computes the mean-centered values of a particular variable for each subject.

A vector.

## Author

Wolfgang Viechtbauer wvb@wvbauer.com

## Examples

# illustrative dataset
dat <- data.frame(subj=rep(1:4, each=5),
obs = 1:5,
age = rep(c(20,31,27,22), each=5),
stress = c(2,3,NA,4,2, 3,3,NA,3,NA, 1,1,2,6,4, 1,2,1,3,1))
dat
#>    subj obs age stress
#> 1     1   1  20      2
#> 2     1   2  20      3
#> 3     1   3  20     NA
#> 4     1   4  20      4
#> 5     1   5  20      2
#> 6     2   1  31      3
#> 7     2   2  31      3
#> 8     2   3  31     NA
#> 9     2   4  31      3
#> 10    2   5  31     NA
#> 11    3   1  27      1
#> 12    3   2  27      1
#> 13    3   3  27      2
#> 14    3   4  27      6
#> 15    3   5  27      4
#> 16    4   1  22      1
#> 17    4   2  22      2
#> 18    4   3  22      1
#> 19    4   4  22      3
#> 20    4   5  22      1

# calculate the mean-centered values of the stress variable
dat$cstress <- calc.mcent(stress, subj, data=dat) dat #> subj obs age stress cstress #> 1 1 1 20 2 -0.75 #> 2 1 2 20 3 0.25 #> 3 1 3 20 NA NA #> 4 1 4 20 4 1.25 #> 5 1 5 20 2 -0.75 #> 6 2 1 31 3 0.00 #> 7 2 2 31 3 0.00 #> 8 2 3 31 NA NA #> 9 2 4 31 3 0.00 #> 10 2 5 31 NA NA #> 11 3 1 27 1 -1.80 #> 12 3 2 27 1 -1.80 #> 13 3 3 27 2 -0.80 #> 14 3 4 27 6 3.20 #> 15 3 5 27 4 1.20 #> 16 4 1 22 1 -0.60 #> 17 4 2 22 2 0.40 #> 18 4 3 22 1 -0.60 #> 19 4 4 22 3 1.40 #> 20 4 5 22 1 -0.60 # calculate the subject-level means of the stress variable dat$mstress <- calc.mean(stress, subj, data=dat, expand=TRUE)
dat
#>    subj obs age stress cstress mstress
#> 1     1   1  20      2   -0.75    2.75
#> 2     1   2  20      3    0.25    2.75
#> 3     1   3  20     NA      NA    2.75
#> 4     1   4  20      4    1.25    2.75
#> 5     1   5  20      2   -0.75    2.75
#> 6     2   1  31      3    0.00    3.00
#> 7     2   2  31      3    0.00    3.00
#> 8     2   3  31     NA      NA    3.00
#> 9     2   4  31      3    0.00    3.00
#> 10    2   5  31     NA      NA    3.00
#> 11    3   1  27      1   -1.80    2.80
#> 12    3   2  27      1   -1.80    2.80
#> 13    3   3  27      2   -0.80    2.80
#> 14    3   4  27      6    3.20    2.80
#> 15    3   5  27      4    1.20    2.80
#> 16    4   1  22      1   -0.60    1.60
#> 17    4   2  22      2    0.40    1.60
#> 18    4   3  22      1   -0.60    1.60
#> 19    4   4  22      3    1.40    1.60
#> 20    4   5  22      1   -0.60    1.60