Last active
December 19, 2015 07:29
-
-
Save philadams-zz/5919286 to your computer and use it in GitHub Desktop.
Sometimes in a survey you have a question of the type, "... please select all that apply". In super awesome survey software, the returned data arrives with a column for each of the options so your software and graphs can easily know about each option's presence of absence. In super awesome survey software that only fails on this one point (like …
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
splitcol = function(x, newcols, targetCol) { | |
# delete commas IN THE STATEMENTS SEPARATED BY COMMAS ROFLMAO | |
x[[targetCol]] = sub('tablet, such', 'tablet such', x[[targetCol]]) | |
x[[targetCol]] = sub('phone, tablet, or', 'phone tablet or', x[[targetCol]]) | |
# check for presence of known examples (newcols[2]) | |
for (i in newcols) { | |
x[[i[1]]] = ifelse(grepl(i[2], x[[targetCol]]), 1, 0) | |
} | |
# check for presence of 'other' strings | |
# basically, split target col on ', ' and see if any of the resulting | |
# strings DON'T match any of our newcol matches | |
match_str <<- paste0(sapply(newcols, function(x) x[-1]), collapse='|') | |
targetCol <<- targetCol | |
x = adply(x, 1, transform, | |
asdf=ifelse(any(!grepl(match_str, | |
strsplit(get(targetCol), ', ')[[1]])), | |
1, 0)) | |
# rename 'other' column <targetCol.'other'> | |
x = rename(x, replace=c('asdf' = paste0(targetCol, ".other"))) | |
# and we're done | |
return(x); | |
} | |
# which animals do you love? pick all that apply... | |
# format for list is c(<newColName>, <patternToMatch>) | |
animalL = list(c('animalLove.cat', 'love cats'), | |
c('animalLove.dog', 'love dogs'), | |
c('animalLove.goldfish', 'my goldfish')) | |
r = splitcol(r, animalL, 'animalLove') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment