create dummy – convert continuous variable into (binary variable) using median

R programming language resources Forums Data manipulation create dummy – convert continuous variable into (binary variable) using median

Tagged: 

Viewing 2 posts - 1 through 2 (of 2 total)
  • Author
    Posts
  • #1011
    tovy
    Member

    Hi, I a continuous variable that I would like to convert to a binary variable based on the median.
    Values greater then the mean should be coded as 1
    Values less then the mean should be coded as 1
    Here’s what I have tried. I don’t get any errors, but it does not update the data. Your assistance is much appreciated. I am SAS programmer trying to use R.
    > Course$grade2 [Course$grade2 ==0] <- (Course$grade2 <median(Course$grade))
    > Course$grade2 [Course$grade2 ==1] <- (Course$grade2 >=median(Course$grade))
    > Course$grade2[1:10]
    [8] 88 85 88 86 87 75 84 64 84 85

    #1014
    bryan
    Participant

    Hi tovy,

    The R idiomatic way to do this is to use an ifelse() statement:

    Course$grade2 <- ifelse(Course$grade >= median(Course$grade), 1, 0)

    For more information on ifelse() you can type ?ifelse at a prompt or just ask here.

    HTH,
    Bryan

    • This reply was modified 10 years, 5 months ago by bryan. Reason: typo
Viewing 2 posts - 1 through 2 (of 2 total)
  • You must be logged in to reply to this topic.
Scroll to top
Privacy Policy