【问题标题】:How to split a column into two in R based on a symbol from scraping result?如何根据抓取结果中的符号将 R 中的一列拆分为两列?
【发布时间】:2019-04-09 15:42:26
【问题描述】:

所以我使用rvest 抓取了 IMDB 网站并遇到了一些拆分问题。我尝试了不同的方法来拆分列,但都失败了。

这是我从 IMDB 网站上抓取信息的代码:

votes_gross <- pagesource %>% html_nodes(".sort-num_votes-visible") %>% html_text()

然后我使用以下代码进行清理和拆分:

votes_gross <- gsub("\r?\n|\r", " ", votes_gross)
votes_gross <- data.frame(votes_gross)
library(tidyr)
votes_gross <- separate(votes_gross,
       col = "votes_gross",
       into = c("Votes", "Gross"),
       sep = "|")

在我执行单独的代码后,数据框立即变为空。我也尝试过使用strsplit,但也失败了。我知道这里还有其他类似的问题,但它们似乎与我的情况不相似。

我希望做这些:

          votes_gross
Votes: 489,547 | Gross: $700.06M
Votes: 615,401 | Gross: $678.82M
Votes: 192,034 | Gross: $608.58M

进入这些:

    Votes         Gross (Millions)
Votes: 489,547    Gross: $700.06
Votes: 615,401    Gross: $678.82
Votes: 192,034    Gross: $608.58

谢谢

【问题讨论】:

    标签: r dataframe split


    【解决方案1】:

    根据?separate

    sep - 如果是字符,则被解释为正则表达式。默认值是匹配任何非字母数字值序列的正则表达式。

    因此,如果我们需要它进行字面计算,请将其放在方括号内([|] 或转义\\|),否则将其视为OR

    library(tidyverse)
    votes_gross <- separate(votes_gross,
       col = "votes_gross",
       into = c("Votes", "Gross"),
       sep = "\\s*[|]\\s*")
    

    【讨论】:

    • 我明白了,它运行良好。谢谢你提到它,我忘了它是一个正则表达式。
    猜你喜欢
    • 1970-01-01
    • 2013-12-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多