0

Very green R user here. I have to categorical variables: One is, committee crime against child or has mental health issues (dichotomous, 1= crime and 0 = mental health) and committed crime against child or has substance abuse issues (dichotomous, 1= crime and 0 = substance abuse). I'd like to combine these groups so I will have a dichotomous, crime against child and mental health or substance abuse group. What would be the best way to do this? I have been playing around with "if" statements but to no avail.

I have been playing around with "if" statements but to no avail. I want to make a new variable in my dataset (com) that combines crime against child (1) and mental health/substance abuse (0)

x$com <- if(x$Group.finalCvsM == 1) {
  x$com("1") }
  if(x$Group.finalCvsS == 1) {
    x$com("1") }
  if(x$Group.finalCvsM == 0) {
    x$com("0") }
    if(x$Group.finalCvsS == 0) {
      x$com("0") }
Nick
  • 21
  • 6
  • Please try to show some [example data](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example), i.e. a few rows of data that show both the variables you have now and what you expect the `com` variable to look like based on the example. One hint: `if` is not good for these kinds of transformations in R, it may be better to look at `ifelse`. – Marius May 28 '19 at 00:15
  • `if` won't work because it expects a scalar value evaluating to true or false. The column in your dataframe is however a vector. Try `ifelse` instead. – coffeinjunky May 28 '19 at 00:16

1 Answers1

1

Because your data is coded as binary 0/1, we can just use the logical OR operator, |.

## very nice way to solve this particular problem
x$com = x$Group.finalCvsM | x$Group.finalCvsS
## The result will be TRUE or FALSE. 
## If you want 1/0 instead, then wrap it in as.integer: 
x$com = as.integer(x$Group.finalCvsM | x$Group.finalCvsS)

In general, ifelse() is a vectorized version of if that is made for cases like this. See the help page ?ifelse for some detail. Here you would use it as:

x$com = ifelse(x$Group.finalCvsM == 1 | x$Group.finalCvsS == 1, 1, 0)

(Note:: since your question doesn't give sample input and desired output, I'm not 100% sure you want OR |. Maybe you want &? Both work fine, use whichever meets your goal.)

Gregor Thomas
  • 136,190
  • 20
  • 167
  • 294