scottsky5
scottsky5

Reputation: 13

How do a "Find and Replace All" in R?

In R I have a dataframe titled GDP. There are three columns, Country, Year and GDP. One of the countries in the column Country is titled "China (People's Republic of)". I would like to replace that text with text that says "China" for all of its instances. What is the best way of doing this? Thank you!

Upvotes: 1

Views: 45

Answers (2)

José
José

Reputation: 931

With tidyverse, you can use str_detect inside ifelse:

library(tidyverse)
GDP <- GDP %>% 
     mutate(Country = ifelse(str_detect("(?i)china", "China",Country)))

Note that I used "(?i)" to make sure that China might be in lower or upper case.

Upvotes: 0

akrun
akrun

Reputation: 887481

We can use grep to locate the elements that have substring 'China' in the 'Country' column and replace those with 'China'. It is assumed that the column is character class

GDP$Country[grep("China", GDP$Country)] <- "China"

Upvotes: 1

Related Questions