R tolower 仅在函数内
R tolower only within function
我想从字符向量中删除单词。我是这样做的:
library(tm)
words = c("the", "The", "Intelligent", "this", "This")
words_to_remove = c("the", "This")
removeWords(tolower(words), tolower(words_to_remove))
这真的很好,但我希望 "Intelligent" 这个词原样返回,意思是 "Intelligent" 而不是“智能。
是否可以仅在函数 removeWords
中使用函数 tolower
?
您可以在此处 grepl
使用基础 R 方法:
words_to_remove = c("the", "This")
pattern <- paste0("\b", words_to_remove, "\b", collapse="|")
words = c("the", "The", "Intelligent", "this", "This")
res <- grepl(pattern, words, ignore.case=TRUE)
words[!res]
[1] "Intelligent"
我在这里使用的技巧是调用 paste
生成以下模式:
\bthe\b|\bThis\b
此模式可以在单个正则表达式评估中确定 words
中的任何字符串是否是要删除的匹配项。
这是另一个使用基础 R 的 %in%
函数的选项:
words = c("the", "The", "Intelligent", "this", "This")
words_to_remove = c("the", "This")
words[!(tolower(words) %in% tolower(words_to_remove))]
%in% returns 对于 "words" 在 "words_to_remove" 列表中的所有情况都为真。对要保留的单词取反。
我想从字符向量中删除单词。我是这样做的:
library(tm)
words = c("the", "The", "Intelligent", "this", "This")
words_to_remove = c("the", "This")
removeWords(tolower(words), tolower(words_to_remove))
这真的很好,但我希望 "Intelligent" 这个词原样返回,意思是 "Intelligent" 而不是“智能。
是否可以仅在函数 removeWords
中使用函数 tolower
?
您可以在此处 grepl
使用基础 R 方法:
words_to_remove = c("the", "This")
pattern <- paste0("\b", words_to_remove, "\b", collapse="|")
words = c("the", "The", "Intelligent", "this", "This")
res <- grepl(pattern, words, ignore.case=TRUE)
words[!res]
[1] "Intelligent"
我在这里使用的技巧是调用 paste
生成以下模式:
\bthe\b|\bThis\b
此模式可以在单个正则表达式评估中确定 words
中的任何字符串是否是要删除的匹配项。
这是另一个使用基础 R 的 %in%
函数的选项:
words = c("the", "The", "Intelligent", "this", "This")
words_to_remove = c("the", "This")
words[!(tolower(words) %in% tolower(words_to_remove))]
%in% returns 对于 "words" 在 "words_to_remove" 列表中的所有情况都为真。对要保留的单词取反。