-2

I have data like this:

data.frame(text1 = c("Amazon", "Google", "other"))

Add I would like to replace whatever is in the list with a specific value

mylist <- c("Amazon", "Google") 

replace what is in the mylist with stock value

Expected output:

data.frame(text1 = c("stock", "stock", "other"))
Nathalie
  • 1,228
  • 7
  • 20

3 Answers3

2

You can do direct assignment :

df$text1[df$text1 %in% mylist] <- 'stock'
df
#  text1
#1 stock
#2 stock
#3 other

Or use replace

df$text1 <- replace(df$text1, df$text1 %in% mylist, 'stock')

data

Read the data as characters :

df <- data.frame(text1 = c("Amazon", "Google", "other"), stringsAsFactors = FALSE)
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
0

Also you can use ifelse() and get a data frame directly

a <- data.frame(text1=ifelse(ls$text1 %in% mylist,"stock",as.character(ls$text1)))
a
  text1
1 stock
2 stock
3 other
Ashish
  • 337
  • 3
  • 11
0

Another base R solution using gsub

df$text1<- gsub(paste0(paste0("\\b",mylist,"\\b"),collapse = "|"),"stock",df$text1)

such that

> df
  text1
1 stock
2 stock
3 other

DATA

df <- data.frame(text1 = c("Amazon", "Google", "other"))

mylist <- c("Amazon", "Google") 
ThomasIsCoding
  • 96,636
  • 9
  • 24
  • 81