1

I am trying to create a dummy variable from a factor variable which looks about like this:

[1]    cva accident w rt hemiparesis          aphasial        dm type ii        htn    
6589 Levels:    cva accident w rt hemiparesis          aphasial        dm type ii        htn     ...

This is the code I have used to create the dummy variable:

random_merge_patients$'MedCond_HTN' <- ifelse(random_merge_patients$'MedCond' %in% "htn",1,0)

I receive no error messages but when I try to view random_merge_patients$'MedCond_HTN' I see that the values are all 0s even if there should be some 1s .

Any ideas what could be wrong with my code?

wibeasley
  • 5,000
  • 3
  • 34
  • 62
coding_is_fun
  • 117
  • 1
  • 14
  • `random_merge_patients$MedCond_HTN<-ifelse(random_merge_patients$MedCond== "htn",1,0)` – BENY Nov 11 '17 at 03:23
  • I have tried == 'htn' but that did not make a difference. It seems that 'htn' is not being recognized in the factor MedCond – coding_is_fun Nov 11 '17 at 03:28
  • is it possible that there is some leading / trailing whitespace? – bouncyball Nov 11 '17 at 03:45
  • not sure about the white space. I have tried to use grepl function which runs and does what i expected: grepl("*htn", random_merge_patients$'MedCond') == "htn" (returns TRUEs and FALSEs) But than the complete function: random_merge_patients$'MedCond_HTN'<-ifelse(grepl("*htn", random_merge_patients$'MedCond') == "htn",1,0) still not picks up "htn" in a factor – coding_is_fun Nov 11 '17 at 03:51
  • It may help to reduce this to a smaller problem with [reproducible data](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example). If you can provide some sample data, it would help. – r2evans Nov 11 '17 at 04:46
  • i figured out. I saved logical grepl() in a new variable, and than put this variable into ifelse(htn==T,1,0) that helped with creation of dummy variables. – coding_is_fun Nov 11 '17 at 23:29

0 Answers0