df[, city:=stringr::str_extract(Company, paste0(cities,collapse = "|"))]
OR
# this also works
df[, city:=cities[sapply(cities, \(x) grepl(x,Company))], by=1:nrow(df)]
Output:
Company city
1: Company 1 Berlin Gmbh. Berlin
2: Dresden Company 2 Gmbh. Dresden
3: Company 3 in Hamburg Hamburg
4: Company 4 Ldt <NA>
Input:
library(data.table)
df =data.table(
Company = c(
"Company 1 Berlin Gmbh.",
"Dresden Company 2 Gmbh.",
"Company 3 in Hamburg",
"Company 4 Ldt")
)
cities = c('Berlin','Dresden','Hamburg')
dputor subset of your data. Here is a guide for doing so: youtu.be/3EID3P1oisg