[英]new column with paste0 in R
我正在尋找一個允許我添加新列的函數,將名為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
我會使用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列中的單詞。 我還重復了“天空”,以顯示這對於一個單詞的每個實例都是如何工作的。
如果要保留原始排序順序,可以在合並之前創建索引變量,然后按該索引變量對輸出重新排序。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.