【问题标题】:Converting vector of strings to tidy format将字符串向量转换为整洁的格式
【发布时间】:2017-12-01 15:28:29
【问题描述】:

这里是网站 url 和一些文本的向量,其中每个 url 和文本用空格分隔:

v <- c("url www.site1.com this is the text of the site" , "url www.site2.com this is the text of the other site" )

我正在尝试转换为整洁的格式:

  url          text
www.site1.com  this is the text of the site
www.site2.com  this is the text of the other site

使用:

df <- data.frame(v)

df %>% separate(v , into=c("url" , "text") , sep = " ")

但这会返回:

url          text
1 url www.site1.com
2 url www.site2.com

是否需要使用替代正则表达式来实现所需的 tibble 格式?

【问题讨论】:

  • df %&gt;% separate(v , into=c("literally_just_url", "url" , "text") , sep = " ") 怎么样。然后,您可以删除无用的 url 列。
  • 另外,记得保存结果:df &lt;- df %&gt;% separate(...)
  • @Gregor 我收到警告消息:“2 个位置的值太多:1、2”为什么会显示? stackoverflow.com/questions/41837430/… 暗示它与使用正则表达式有关?
  • @Gregor 使用df %&gt;% separate(v , into=c("literally_just_url", "url" , "text") , sep = " ") 将第一个单词放入文本列,而不是整个文本。
  • 显示是因为有2个以上的空格,所以在一个空格上分割时有3个以上的compenents。使用extra 参数进行修复。

标签: r


【解决方案1】:
v <- c("url www.site1.com this is the text of the site" , "url www.site2.com this is the text of the other site" )
df = data.frame(v)
tidyr::separate(df, v, into = c("literally_just_url", "url", "text"),
                sep = " ", extra = "merge")
#   literally_just_url           url                               text
# 1                url www.site1.com       this is the text of the site
# 2                url www.site2.com this is the text of the other site

【讨论】:

    【解决方案2】:

    类似的东西呢:

    library(tidyverse)
    
    tibble(v = v) %>% 
      mutate_at("v", str_replace, pattern = "^url ", replacement = "") %>% 
      separate(v, c("url", "text"), sep = " ", extra = "merge")
    

    【讨论】:

      【解决方案3】:

      这个怎么样,

      df %>% 
      extract(v, into = c('url', 'text'),  regex = "url\\s+(\\S+)\\s+([A-Za-z ]+)")
      

      正则表达式的解释:匹配 url 后跟一个空格,使用 url\\s。后跟要匹配的多个不带空格的字母数字字符(\\S+)。后跟另一个空格\\s。最后是带有空格的文本的其余部分([A-Za-z ]+)

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-01-07
        • 1970-01-01
        • 2017-02-22
        • 2016-05-03
        • 1970-01-01
        相关资源
        最近更新 更多