Creating new variable using conditions of two variables

Hi,

I'm new to R programming and taking an online course to learn more. I've come across a problem that I can understand and was wondering if anyone can point me in the right direction and explain what I did wrong.

I'm trying to categorize my data variable hdl based on gender and hdl levels. I enter the code below

gender<-mydata$gender
hdlcat<-ifelse(gender="male" & hdl<40, "at risk",
ifelse(gender="male" & hdl>=40, "desirable",
ifelse(gender="female" & hdl<50, "at risk",
ifelse(gender="female" & hdl>=50, "desirable", NA))))

When I run the code I'm getting this error message:

hdlcat<-ifelse(gender="male" & hdl<40, "at risk",

  •               ifelse(gender="male" & hdl>=40, "desirable",
    
  •                   ifelse(gender="female" & hdl<50, "at risk",
    
  •                          ifelse(gender="female" & hdl>=50, "desirable", NA)))))
    

Error in ifelse(gender = "male" & hdl < 40, "at risk", ifelse(gender = "male" & :
unused argument (gender = "male" & hdl < 40)

I don't quite understand this "unused argument (gender = "male" & hdl < 40)" and honestly I've tried random things to just get the code to work, but not understanding what I'm doing wrong?

Any help is appreciated :slight_smile:

So of course I think I figured it out after questioning what I did wrong, but I think I was just being way too detailed in my coding also the double "==" instead of "=". Please correct me if I am wrong but I used the following code and it worked :

hdlcat<-ifelse(hdl <40 & gender=="male", "at risk",
ifelse(hdl<50 & gender=="female", "at risk", "desirable")

1 Like

You're correct. when using ifelse statement, we need to use "==" instead of "=". You could also use mutate in tidyverse to new variables using conditions

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.