Creating New Numeric Variable based on a mathematical expression

Hi @shoaibraee , thanks for posting again! I’ll try to help.

In the future, I’ll be able to answer more quickly if you can include a small piece of your data too - see this post on how to use the {datapasta} r package to do that.

Now to your case_when() issue:

  • case_when() expects all possible values on the right side of the ~ to be of the same class. Assuming that your ExistingVAR_numeric is class numeric, the 6th and 7th options you have written for “NO” and “na” that assign the character value “NA” will cause a problem because “NA” is class character, not numeric like the other options.

  • Try removing the 6th and 7th options from your command. case_when() will default to assigning “NO” and “na” (and anything else not addressed in your command) to NA Best of all, it will automatically use the NA of the correct class (yes, annoyingly there are variations of NA with different classes, such as NA_character. You can read more about this here.)

Does that work?

Finally, it is best to build your case_when() command one step at a time. Add a line, run the command, look at your data to see the changes. If you get an error, then you will know exactly which line in the case_when() command caused the error.

2 Likes