【问题标题】:How do I split a line via a delimiter?如何通过分隔符拆分行?
【发布时间】:2022-01-13 09:10:11
【问题描述】:

我有一个数据框。

[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('你叫什么名字?问题2。你住在哪里?问题3。~~~','问题')

标签: r regex split delimiter


【解决方案1】:

之后使用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?')

【讨论】:

    【解决方案2】:

    这是使用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.  ~~~~')
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-06-14
      • 1970-01-01
      • 1970-01-01
      • 2013-03-03
      • 2019-05-11
      • 2015-02-05
      • 2014-03-02
      • 2012-03-15
      相关资源
      最近更新 更多