您可以使用命名單位向量和Vectorize grep表示outer。在處理if未找到匹配項的情況下,我們可以拋出NA。 units <- c(kilogram="kg", meters="meters", euro="cost", euro="price", variable='var')dat[, unit:=apply(outer(units, description, Vectorize(grepl)), 2, \(x) if (any(x)) names(which(x)) else NA)]dat# var_nam description unit# 1: some_var this is some var kg kilogram,variable# 2: some_var this is some NA# 3: other_var this is meters for another var meters,variable# 4: extra_var the price of apples euro# 5: another_var cost of goods sold euro Data: dat <- structure(list(var_nam = c("some_var", "some_var", "other_var", "extra_var", "