dimanche 5 juillet 2020

Recode continuous variable in R based on conditions

I want to "translate" a syntax written in SPSS into R code but am a total beginner in R and struggling to get it to work.

The SPSS syntax is

DO IF  (Geschlecht = 0).
RECODE hang0 (SYSMIS=SYSMIS) (Lowest thru 22.99=0) (23 thru 55=1) (55.01 thru Highest=2)  
    INTO Hang.
ELSE IF (Geschlecht = 1).
RECODE hang0 (SYSMIS=SYSMIS) (Lowest thru 21.99=0) (22 thru 54=1) (54.01 thru Highest=2) 
    INTO Hang.
END IF.

I have installed the "car"-package in R but I neither get the "range" recoding to work (I have tried

td_new$Hang <- recode(td_new$hang0, "0:22.99=0; 23:55=1; else=2")

nor do I manage to work with the if-else-function. My last attempt was

if(td_new$Geschlecht == 0){
  td_new$Hang <- td_new$hang0 = 3
} else if (td_new$Geschlecht == 1) {
  td_new$Hang <- td_new$hang0 = 5)
} else
  td_new$hang0 <- NA

(this was without the recoding, just to test the if-else function).

Would be very happy if someone helped!

Thanks a lot in advance :)!

Sorry, edited to add: The data structure looks as follows:

Geschlecht  hang0
0           15
1           45
1            7
0           11

And I want to recode hang0 such that for boys (Geschlecht = 0): all values < 23 = 0, values between 23 and 55 = 1, all values > 55 = 2 and for girls (Geschlecht = 1): all values < 22 = 0, values between 23 and 54 = 1, all values > 54 = 2

Aucun commentaire:

Enregistrer un commentaire