I have a condition with the levels positive and negative. I want to create numeric variables (contrast coding), so the positive = 0.5 and negative = -0.5.
I tried a lot, but I don't know how to achieve this.
I am happy for help!
I have a condition with the levels positive and negative. I want to create numeric variables (contrast coding), so the positive = 0.5 and negative = -0.5.
I tried a lot, but I don't know how to achieve this.
I am happy for help!
The general way of recoding a factor is to create a new factor with the desired levels and labels:
recoded = factor(x, levels = c('negative', 'positive'), labels = c(-0.5, 0.5))
But now you still have a factor; to get numeric values, you need to convert it:
numeric_values = as.numeric(as.character(recoded))
Note that it’s important to first call as.character
! If you directly called as.numeric
, you’d instead the numeric levels (1, 2), not the factor labels.
Since the above is somewhat convoluted, the ‘forcats’ package provides a shortcut to recode the factor:
recoded = forcats::fct_recode(x, `-0.5` = 'negative', `0.5` = 'positive')
As an alternative you can skip the recoding step, and encode your values in a lookup vector instead:
mapping = c(negative = -0.5, positive = 0.5)
numeric_values = unname(mapping[x])