KyleF
KyleF

Reputation: 135

Replacing character string with another character string

I have a data frame for which I am attempting to replace certain values with others. So, as a small example, I have a dummy data frame of:

dummy<-c("1","2","3","4")
dummy<-data.frame(dummy)
dummy$dummy<-as.character(dummy$dummy)

odd<-c("1","3")

replace(dummy$dummy, dummy$dummy==odd, "odd")

#> [1] "odd" "2"   "3"   "4" 

Why would this only replace "1" with "odd" and not "3"?

My actual dataset has more information in it (it is restaurant cuisine types and I need to replace the types of cuisine by a more general category. For example, I have the cuisine types "Italian" and "French" in my dataset that need to be replaced with "European", and cuisine types "Southwestern" and "Pacific Northwestern" that need to be replaced with "American".

Is the above idea the most efficient way to do this?

Upvotes: 2

Views: 3374

Answers (3)

akrun
akrun

Reputation: 886948

We can do this in base R

levels(df$dummy)[levels(df$dummy) %in% c(1, 3)] <- "odd"
df
#  dummy
#1   odd
#2     2
#3   odd
#4     4

data

df <- data.frame(dummy = c("1","2","3","4"))

Upvotes: 0

akaDrHouse
akaDrHouse

Reputation: 2240

It sounds like your replacement is an actual variable; if so, you can replace with an ifelse statement as follows:

df <- data.frame(dummy = c("1","2","3","4"))
df$dummy <- ifelse(df$dummy %in% c(1,3), "Odd", df$dummy)
df

  dummy
1   Odd
2     2
3   Odd
4     4

Upvotes: 0

austensen
austensen

Reputation: 3007

Like epi99 suggested, you can use stringr::str_replace() for this. You might also want to look over their guide to using Regular Expressions as well.

library(dplyr)
library(stringr)

df <- data_frame(dummy = c("1","2","3","4"))

df %>% mutate(dummy = str_replace(dummy, "1|3", "odd"))

#> # A tibble: 4 x 1
#>   dummy
#>   <chr>
#> 1   odd
#> 2     2
#> 3   odd
#> 4     4

Upvotes: 3

Related Questions