【问题标题】:From tags to columns text从标签到列文本
【发布时间】:2020-08-04 18:22:40
【问题描述】:

在具有格式标签的文本中,例如

data.frame(id = c(1, 2), text = c("something here <h1>my text</h1> also <h1>Keep it</h1>", "<h1>title</h1> another here"))

#   id                                                  text
# 1  1 something here <h1>my text</h1> also <h1>Keep it</h1>
# 2  2                           <h1>title</h1> another here

如何根据下一个&lt;h1&gt; &lt;/h1&gt; 的开始和结束时间将文本滑入不同的列。输出示例:

data.frame(id = c(1, 2), my_text = c("also", 0), keep_it = c(0, 0), title = c(0, "another here"))

#   id my_text keep_it        title
# 1  1    also       0            0
# 2  2       0       0 another here

将 0 而不是 NA 插入到后面不存在的文本或输入行中不存在特定列的文本

【问题讨论】:

    标签: r


    【解决方案1】:

    tidyverse 解决方案:

    library(tidyverse)
    
    map_dfr(df$text, ~ str_match_all(.x, "<h1>(.*?)</h1>([^<]*)")[[1]] %>%
        as.data.frame %>% select(-1) %>% deframe) %>%
      mutate(across(everything(), ~ str_squish(.x) %>%
        replace(is.na(.x) | .x == "", 0)))
    
    # # A tibble: 2 x 3
    #   `my text` `Keep it` title       
    #   <chr>     <chr>     <chr>       
    # 1 also      0         0           
    # 2 0         0         another here
    

    【讨论】:

      猜你喜欢
      • 2017-11-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-09
      相关资源
      最近更新 更多