需要帮助将R中的“[some words] [space] [more words]”替换为[some word]

问题描述 投票:0回答:1

我有以下数据。

    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]”

r web-scraping replace substring
1个回答
0
投票

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

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
© www.soinside.com 2019 - 2024. All rights reserved.