I have free-text data with numerous references to specific questions, and I'd like to organize it as shown below.
I'm able to create columns that note mentions of a certain topic (if the respondent references it by number), but I'd like a way to extract all of the text following the number, until another number is encountered.
Thanks in advance for any help!
library(tidyverse, warn.conflicts = F)
# Data
df <- data.frame(comment = c("topic 1: this is fine. 4 this is fine too. #9 not so good", "1 ok this is fine. 17 i do not like this idea. 25 great idea 43 cool idea"))
# I can identify the mentions if a respondent specifies the number they are responding to
df <- df %>%
mutate(mention = map(str_extract_all(comment, "[0-9]+"), as.numeric)) %>%
unnest_wider(col = mention, names_sep = "_")
# Ideal output
df_ideal <- structure(list(comment = c("topic 1: this is fine. 4 this is fine too. #9 not so good",
"1 ok this is fine. 17 i do not like this idea. 25 great idea 43 cool idea"
), mention_1 = c(1, 1), mention_2 = c(4, 17), mention_3 = c(9,
25), mention_4 = c(NA, 43), comment_1 = c("1: this is fine.",
"1 ok this is fine."), comment_2 = c("4 this is fine too.", "17 i do not like this idea."
), comment_3 = c("9 not so good", "25 great idea"), comment_4 = c(NA,
"42 nice idea")), row.names = c(NA, -2L), class = c("tbl_df",
"tbl", "data.frame"))
Created on 2021-04-18 by the reprex package (v2.0.0)