Home > Enterprise >  Recoding a column in a data.frame conditional on another column
Recoding a column in a data.frame conditional on another column

Time:09-29

In my tutorial dataframe below, I'm trying to recode column schgend according to the following condition:

In rows where we have: sex=="girl" & schgend =="girlsch" OR we have: sex=="boy" & schgend=="boysch", the values in column schgend must be recoded to "same-sex". Otherwise, the values in column schgend should remain unchanged.

I'm wondering, though, why my ifelse() call doesn't produce my desired outcome, is there a fix?

library(R2MLwiN)
data("tutorial")

transform(tutorial, schgend_new =ifelse(sex=="girl" & schgend=="girlsch" ||
                        sex=="boy" & schgend=="boysch","same-sex",schgend))

CodePudding user response:

You can do it using dplyr

library(dplyr)


tutorial_recoded <- tutorial %>%
  mutate(schgend_new = ifelse(sex=="girl" & schgend=="girlsch" | 
           sex=="boy" &  schgend=="boysch",
         "same-sex", schgend))

CodePudding user response:

Try this:

tutorial$schgend_new <- ifelse(
    (tutorial$sex=="girl" & tutorial$schgend=="girlsch") |
    (tutorial$sex=="boy" & tutorial$schgend=="boysch"),
    "same-sex",
    tutorial$schgend)
  • Related