Let's say I have a data frame like this:
dat<- data.frame(ID= rep(c("A","B","C","D"),4),
test= rep(c("pre","post"),8),
item= c(rep("item1",8),rep("item2",8))
answer= c("undergraduateeducation_graduateorprofessionalschool_employment",
"graduateorprofessionalschool",
"undergraduateeducation_graduateorprofessionalschool_employment_volunteeractivityoroutreach",
"volunteeractivityoroutreach",
"undergraduateeducation_employment_volunteeractivityoroutreach",
"employment",
"volunteeractivityoroutreach",
"undergraduateeducation_graduateorprofessionalschool_employment_volunteeractivityoroutreach",
"undergraduateeducation_graduateorprofessionalschool_employment",
"graduateorprofessionalschool",
"undergraduateeducation_graduateorprofessionalschool_employment_volunteeractivityoroutreach",
"volunteeractivityoroutreach",
"undergraduateeducation_employment_volunteeractivityoroutreach",
"employment",
"volunteeractivityoroutreach",
"undergraduateeducation_graduateorprofessionalschool_employment_volunteeractivityoroutreach"))
The answer column represents a "select all the apply" answer type- where the underscore separates selected answer options. For each ID, test and item, I would like to change this single variable to multiple presence/absence variables indicating the presence or absence of that answer component in the string. 1 indicates that answer option was present in the respondents answer and 0 represents that component was absent. The variables undergraduate, graduate, employment and volunteer in res correspond to the following strings in answer, respectivley: undergraduateeducation, graduateorprofessionalschool,employment, volunteeractivityoroutreach. White spaces were removed.
The result data frame would look as follows:
res<- data.frame(ID= rep(c("A","B","C","D"),4),
test= rep(c("pre","post"),8),
item= c(rep("item1",8),rep("item2",8)),
undergraduate= c(1,0,1,0,1,0,0,1,1,0,1,0,1,0,0,1),
graduate= c(1,1,1,0,0,0,0,1,1,1,1,0,0,0,0,1),
employment=c(1,0,1,0,1,1,0,1,1,0,1,0,1,1,0,1),
volunteer=c(0,0,1,1,1,0,1,1,0,0,1,1,1,0,1,1))