Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating an indicator variable using partial string matching

I am trying to create an indicator variables for different races/ethnicities in my data. In my data ('mydata') I have a variable called "Race". This variable has the output for every box a person marked under race on a questionnaire. So it looks something like this:

ID   Race
6    American Indian or Alaska Native, Black or African American, Hispanic or Latino
7    Hispanic or Latino
10   Native Hawaiian or Other Pacific Islander
11   Hispanic or Latino, White
29   White
30   Black or African American
31   American Indian or Alaska Native, Hispanic or Latino, White

I want to create a variable so that if someone for example said that they were Hispanic, ignoring what else they said, under the new "Hispanic" variable they would get a "1" or if they did not say they were Hispanic then "Hispanic" would get a 0.

I know this entails using partial string matching but I am having difficulty getting the output that I would like. I have made multiple attempts with little luck. Here is the code for my last attempt:

if(mydata[grep("Hispanic", mydata$Race)]) {
  Hispanic<-1
 } else {
  Hispanic<-0
 }      
like image 556
user3008983 Avatar asked Apr 20 '26 11:04

user3008983


1 Answers

You may use grepl which "returns a logical vector (match or not for each element of x)" (from ?grepl). The resulting logical vector can then be converted to 0 (FALSE) or 1 (TRUE) by using as.integer:

mydata$Hispanic <- as.integer(grepl(pattern = "Hispanic", x = mydata$Race))
mydata$Hispanic
# [1] 1 1 0 1 0 0 1
like image 177
Henrik Avatar answered Apr 22 '26 06:04

Henrik



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!