【问题标题】:Extracting information between special characters in a column in R在R中的列中的特殊字符之间提取信息
【发布时间】:2022-11-17 01:08:35
【问题描述】:

很抱歉,因为我觉得这个问题的版本已被问过很多次,但我根本无法从其他示例中找到适用于这种情况的代码。我有一列,我想要的所有信息都存储在两组“%%”之间,我想在两组括号之间提取这些信息并将其放入一个新列中,在本例中称为 df$empty .

这是一个很长的专栏,但在所有情况下,我只需要括号之间的信息。有没有办法在整个专栏中对此进行编码?

具体来说,我希望在此示例中有一个看起来像“信息”、“通缉令”的新列。


empty <- c('NA', 'NA')
information <- c('notimportant%%information%%morenotimportant', 'ignorethis%%wanted%%notthiseither')

df <- data.frame(information, empty)

【问题讨论】:

    标签: r string dataframe character extract


    【解决方案1】:

    在这种情况下你可以这样做:

    df$empty <- sapply(strsplit(df$information, '%%'), '[', 2)
    
    #                                   information       empty
    # 1 notimportant%%information%%morenotimportant information
    # 2           ignorethis%%wanted%%notthiseither      wanted
    

    也就是说,将文本拆分为 '%%' 并获取结果向量的第二个元素。

    【讨论】:

      猜你喜欢
      • 2017-11-10
      • 2015-06-23
      • 1970-01-01
      • 1970-01-01
      • 2019-01-28
      • 2020-12-06
      • 1970-01-01
      • 1970-01-01
      • 2021-07-18
      相关资源
      最近更新 更多