在将R中的[某些单词] [空格] [更多单词]替换为[某些单词]时需要帮助

时间:2019-03-11 23:29:28

标签: r web-scraping replace substring

我有以下数据。

    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 [some word]”替换所有包含“ Zurich”(4,5,6)的字符串

1 个答案:

答案 0 :(得分:0)

这个问题有点模糊,因为我们没有被告知数据的存储结构。但是假设数据存储在数据框中,下面的代码应该起作用: / p>

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