如何通过分隔符拆分一行?

How do I split a line via a delimiter?

我有一个数据框。

[1]  Question  1. What is your name? Question  2. Where do you live? Question  3. ~~~
[2]  Question  1. What are your hobbies? Question  2. What is your school? Question  3. ~~~

我想以“问题”作为分隔符来拆分行。我能解决这个问题吗?

结果:

[1] Question  1. What is your name?
[2] Question  2. Where do you live?
[3] Question  3. ~~~
[4] Question  1. What are your hobbies?
[5] Question  2. What is your school?
[6] Question  3. ~~~

使用 strsplit 和环顾四周,之后 trimws

strsplit(x, '(?<=\s)(?=Question)', perl=TRUE) |> lapply(trimws)
# [[1]]
# [1] "Question  1. What is your name?" "Question  2. Where do you live?" "Question  3.  How old are you?" 
# 
# [[2]]
# [1] "Question  1. What are your hobbies?"  "Question  2. What is your school?"   
# [3] "Question  3.  What are your hobbies?"

数据:

x <- c('Question  1. What is your name? Question  2. Where do you live? Question  3.  How old are you?',
       'Question  1. What are your hobbies? Question  2. What is your school? Question  3.  What are your hobbies?')

这是使用 stringr::str_split 的单行解决方案。使用 unlist 取消列出。

str_split(x, "(?<=.)(?=Question)")

[[1]]
[1] "Question  1. What is your name? " "Question  2. Where do you live? "
[3] "Question  3.  ~~~~"              

[[2]]
[1] "Question  1. What are your hobbies? " "Question  2. What is your school? "  
[3] "Question  3.  ~~~~" 

数据

x <- c('Question  1. What is your name? Question  2. Where do you live? Question  3.  ~~~~',
       'Question  1. What are your hobbies? Question  2. What is your school? Question  3.  ~~~~')