My question is very similar to this one and @rjen's answer almost works, but I am having trouble adapting and understanding it well enough to make it work 100%.
I have some survey data relating to a "check all that apply" question. There are 13 predefined choices, all of them without commas, and the respondents could also write their own answers (below, respondent 1 wrote Discord, for example, and respondent 3 with "I like to share this with friends, family and other people). Therefore, my input data looks like this:
Q1 |
---|
Twitter, Facebook, Discord |
Facebook, WhatsApp, Twitter |
WhatsApp, Twitter, I like to share this with friends, family and other people |
I'd like to have this output:
Q1.1 | Q1.2 | (...)Q1.13 | Others |
---|---|---|---|
0 | 1 | 0 | Discord |
0 | 0 | 1 | 0 |
1 | 0 | 0 | I like to share this with friends, family and other people |
1 | 0 | 0 | 0 |
I've tried to get there by the following code process:
Q1_names <- c("Blog ou site pessoal", "Facebook", "Messenger", "Instagram", "Reddit", "Signal", "Telegram", "TikTok", "Twitter", "WhatsApp", "Youtube", "Não me sinto seguro para me expressar em nenhum ambiente digital", "Nenhuma das anteriores")
amb_seg_correct1 <- df1 %>%
mutate(Q1.1 = +(str_detect(Q1, Q1_names[1])),
Q1.2 = +(str_detect(Q1, Q1_names[2])),
Q1.3 = +(str_detect(Q1, Q1_names[3])),
Q1.4 = +(str_detect(Q1, Q1_names[4])),
Q1.5 = +(str_detect(Q1, Q1_names[5])),
Q1.6 = +(str_detect(Q1, Q1_names[6])),
Q1.7 = +(str_detect(Q1, Q1_names[7])),
Q1.8 = +(str_detect(Q1, Q1_names[8])),
Q1.9 = +(str_detect(Q1, Q1_names[9])),
Q1.10 = +(str_detect(Q1, Q1_names[10])),
Q1.11 = +(str_detect(Q1, Q1_names[11])),
Q1.12 = +(str_detect(Q1, Q1_names[12])),
Q1.13 = +(str_detect(Q1, Q1_names[13])),
Others = str_remove_all(Q1, str_c(Q1_names, collapse = '|')),
Others = if_else(str_sub(Others, 1, 12) == ', ',
str_sub(Others, 13),
Others),
Others = if_else(Others == '', '0', Others))
It almost works, the only problem is that some of the options (the one's where the respondent has filled the max amount of options, aka 3) are coming back as ",,"
Others |
---|
Discord |
,, |
I like to share this with friends, family and other people |
0 |
Any ideas of how to fix it? :)