-1

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!

Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214
Nini
  • 1
  • It would be easier to help if you create a small reproducible example along with expected output. Read about [how to give a reproducible example](http://stackoverflow.com/questions/5963269). Have a look at `?ifelse`. – Ronak Shah Jul 30 '21 at 09:32

1 Answers1

0

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])
Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214