Try this hack, starting with a text file:
"", "textOriginal"
"1," "some text"
"2," "some text"
"3," "some text"
"4," "some
more
text"
The code:
quux <- readLines("quux.txt")
quux2 <- stringr::str_extract_all(paste(paste0(quux, ifelse(cumsum(nchar(gsub('[^"]', '', quux))) %% 2 == 0, ",", "\n")), collapse = ""), '"[^"]*"')[[1]]
quux2
# [1] "\"\"" "\"textOriginal\"" "\"1,\""
# [4] "\"some text\"" "\"2,\"" "\"some text\""
# [7] "\"3,\"" "\"some text\"" "\"4,\""
# [10] "\"some\n more\n text\""
data.frame(matrix(quux2, ncol = 2, byrow = TRUE))
# X1 X2
# 1 "" "textOriginal"
# 2 "1," "some text"
# 3 "2," "some text"
# 4 "3," "some text"
# 5 "4," "some\n more\n text"
The overall goal is to:
- read this in as text;
- add commas to sentences that are quote-complete and add newlines (
\n) to lines that are not;
- concatenate all of that into one continuous vector;
- extract all sequences of the literal
", zero or more non-", then another ";
- use a
matrix formation to construct the data.frame. (Rename as desired.)
Walk-through:
cumsum(nchar(..)) counts the number of quotation marks on a line. We do it cumulative so that (for instance, the more line is counted as still being incomplete.
ifelse(..) based on whether cumsum is odd (incomplete quotes) or even (quote-complete), append a newline or a comma;
paste0 (append) this to the original lines;
paste (concatenate) all things into one string;
- then extract all lengths of string that have a double-quote, some (or none) non-quotes, then another double-quote.
You can clean it up if you want with:
# quux3 <- ...above...
quux3[] <- lapply(quux3, gsub, pattern = '^"|\"$', replacement = '')
quux3
# X1 X2
# 1 textOriginal
# 2 1, some text
# 3 2, some text
# 4 3, some text
# 5 4, some\n more\n text