dgr379
dgr379

Reputation: 345

Changing several names at once in column in data.frame in R

I want to change the names of the column PitchAccent in my data data.frame that are not no into yes using something like:

data$Pitch<-gsub(!("no"), "yes", data$PitchAccent)

Saving it into a new column.

Since I have about 10 different names that I want to change into yes it would be annoying to run data$Pitch<-gsub("H*L","yes",data$PitchAccent) that many times.

Is there a better way of doing this?

EDIT:

In PitchAccent column we have:

enter image description here

Upvotes: 0

Views: 40

Answers (1)

Felipe Alvarenga
Felipe Alvarenga

Reputation: 2652

From your question I don't really know if you have many different words alongside "yes" so to make sense of using gsub or something like it.

If you only have single words in your PitchAccent column

yes_words = c(... words you want to change into "yes" ...)
data$Pitch <- data$PitchAccent
data$Pitch[data$Pitch %in% yes_words] <- "yes"

If you have to detect those words

library(stringr)
yes_ind = str_detect(data$PitchAccent, c("strings that identify which elements you need to change"))

data$Pitch <- data$PitchAccent
data$Pitch[yes_ind] <- "yes"

Upvotes: 2

Related Questions