【问题标题】:Need help in replacing a "[some word][space][more words]" to [some word] in R需要帮助在 R 中将“[some word][space][more words]”替换为 [some word]
【发布时间】:2019-08-02 08:39:19
【问题描述】:

我有以下数据。

    Company
1   Progressive Corp.
2   Travelers Companies Inc.
3   Progressive Finance  Corp.
4   Zurich Insurance Group (3)
5   Zurich Financial Services Ltd
6   Zurich  Ltd
7   Berkshire Hathaway Inc.
8   Auto-Owners Insurance Co.
9   Berkshire Finance Inc.
10  AmTrust Financial Services

例如:我需要将所有包含“Zurich”(4,5,6) 的字符串替换为“Zurich [some word]”

【问题讨论】:

  • 我注意到您的示例数据似乎不包含我们应该替换的任何字符串。
  • 您的样本数据和预期输出不是很具体;通常,有不同的方法可以解决您的问题,但是由于您没有提供足够的信息,因此很难说这些方法中的任何一种能在多大程度上推广到您的更大数据集。例如,您是否总是将"[some word][space][more words]" 替换为"[some word] US"?这里的关键是提供最少但有代表性的样本数据并提供匹配的预期输出。
  • 对于您给出的示例 gsub 将起作用。 gsub(pattern, replacement, string)。但是,如果您要进行多项不同的更改,则必须尝试其他方法。
  • 我有以上数据,我需要将“[some word][space][more words]”替换为“[some word]”。
  • 所以"Zurich Insurance Group (3)” 应该变成”Zurich”"Berkshire Finance Inc.” 应该变成“Berkshire”?

标签: r web-scraping replace substring


【解决方案1】:

这个问题有点模糊,因为我们没有被告知存储数据的结构。但是假设数据存储在数据帧中,下面的代码应该可以工作:

company.data = data.frame(
c("Progressive Corp.",
"Travelers Companies Inc.",
"Progressive Finance  Corp.",
"Zurich Insurance Group (3)",
"Zurich Financial Services Ltd",
"Zurich  Ltd",
"Berkshire Hathaway Inc.",
"Auto-Owners Insurance Co.",
"Berkshire Finance Inc.",
"AmTrust Financial Services"), stringsAsFactors = F)

names(company.data) = "company"

change.index = which(grepl("Zurich", company.data$company))

company.data$company[change.index] = "Zurich"

> company.data
                      company
1           Progressive Corp.
2    Travelers Companies Inc.
3  Progressive Finance  Corp.
4                      Zurich
5                      Zurich
6                      Zurich
7     Berkshire Hathaway Inc.
8   Auto-Owners Insurance Co.
9      Berkshire Finance Inc.
10 AmTrust Financial Services

【讨论】:

    猜你喜欢
    • 2016-04-08
    • 1970-01-01
    • 2017-05-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多