val
val

Reputation: 1709

Why is this gsub not working in R

I want to replace every word beginning with Jo with the word Joburg, however this code isn't working and I don't understand why.

gsub("^Jo\\w+","Joburg",DF[,4:9])

My data frame has 10 columns and i'm looking to do the replacement in columns 4 to 9, all of which are factors.

When I run unique() afterwards i still get the original list of distinct words starting with Jo, instead of only the word Joburg throughout.

Upvotes: 3

Views: 10272

Answers (2)

Lohith Arcot
Lohith Arcot

Reputation: 1186

If you would like to replace content for one column only you can do as follows:

data$colname <- gsub ("^Jo\\w+","Joburg", data$colname)

you can also convert factor to character if there are too many factors and then use gsub

data$column_name <- as.character(data$column_name)

Make sure that the library for gsub function is loaded.

Upvotes: 0

akrun
akrun

Reputation: 887971

If we are working on a data.frame, then loop through the columns and apply the gsub

DF[4:9] <- lapply(DF[4:9], function(x) gsub("^Jo\\w+","Joburg",x))

This can also be done with sub and without an anonymous function call

DF[4:9] <- lapply(DF[4:9], sub, pattern = "^Jo\\w+", replacement = "Joburg")

data

set.seed(24)
DF <- as.data.frame(matrix(sample(c("Joan", "abf", "Jedi", "acf"), 9*4,
                       replace=TRUE), ncol=9))

Upvotes: 2

Related Questions