'How to mean center variables based on binary condition in r

I have a dataframe ("md") containing several variables, of which one is binary ("adopter"). I would like to mean center three of the other (continous) variables, let's say X, Y, and Z, but only for the ones where adopter = 1. The others, for which adopter = 0, should remain unchanged. In the end I would like to end up with a new dataframe containing all variables as before, but with the X, Y, and Z for which adopter = 1 being mean centered, while leaving the X, Y, and Z for which adopter = 0 being unchanged.

My dataframe looks like this (117 observations in total):

adopter X Y Z A B
0 0.5 2.3 4.5 3 4.7
1 1.5 6.5 -2.3 69.3 -2.5
... ... ... ...

So the new dataframe should contain the center means of X, Y, and Z of the second row in this example, as adopter=1, and leave the rest unchanged.

I know how to mean center all X, Y, and Z:

md_cen <- md

covs_to_center <- c("X", "Y", "Z")
md_cen[covs_to_center] <- scale(md_cen[covs_to_center], 
                                scale = FALSE)

But I cannot figure out how to get the "only if adopter == "1" " into it. I also tried applying a function:

center_apply <- function(x) {
  apply(x, 2, function(y) y - mean(y))}

However, this leaves me again with the mean centered versions for all X, Y, Z, of course, and on top the new dataset contains only those three variables.

Can anyone help me out here, please?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source