R中带有paste0的新列

时间:2019-03-22 16:36:08

标签: r string tm

我正在寻找一个函数,该函数允许我添加新列以将称为ID的值添加到字符串,即:

我有一个带有您的ID的单词列表:

car = 9112
red = 9512
employee = 6117
sky = 2324

words<- c("car", "sky", "red", "employee", "domestic")
match<- c("car", "red", "domestic", "employee", "sky")

通过读取一个excel文件进​​行比较,如果发现值等于我的矢量单词,它将用其ID替换该单词,但保留原始单词

    x10<- c(words)# string

words.corpus <-  c(L4$`match`) #  pattern
idwords.corpus <- c(L4$`ID`) # replace
words.corpus <- paste0("\\A",idwords.corpus, "\\z|\\A", words.corpus,"\\z")

vect.corpus <- idwords.corpus
names(vect.corpus) <- words.corpus

data15 <- str_replace_all(x10, vect.corpus)

结果:

data15:

" 9112", "2324", "9512", "6117", "employee"

我要寻找的是用ID添加新列,而不是用ID替换单词

words      ID
car           9112
red          9512
employee 6117
sky            2324
domestic domestic

1 个答案:

答案 0 :(得分:0)

我将使用 data.table 基于固定字词值进行快速查找。尽管并不能100%清楚您的要求,但听起来好像您想在匹配的情况下用索引值替换单词,或者如果没有则将其保留为单词。这段代码可以做到:

library("data.table")

# associate your ids with fixed word matches in a named numeric vector
ids <- data.table(
  word = c("car", "red", "employee", "sky"),
  ID = c(9112, 9512, 6117, 2324)
)
setkey(ids, word)

# this is what you would read in
data <- data.table(
  word = c("car", "sky", "red", "employee", "domestic", "sky")
)
setkey(data, word)

data <- ids[data]
# replace NAs from no match with word
data[, ID := ifelse(is.na(ID), word, ID)]

data
##        word       ID
## 1:      car     9112
## 2: domestic domestic
## 3: employee     6117
## 4:      red     9512
## 5:      sky     2324
## 6:      sky     2324

此处“国内”不匹配,因此它仍保留为ID列中的单词。我还重复了“天空”,以说明这对于一个单词的每个实例将如何工作。

如果要保留原始排序顺序,可以在合并之前创建一个索引变量,然后按该索引变量对输出重新排序。