R:从向量元素中移除向量元素
R: Remove vector elements from vector elements
我觉得标题有点混乱,但我的问题是:
我有 2 个向量,一个包含一些文本,另一个包含一些短语
text <- c("this is some text","some elements should be removed", "i hope you can help me with this text element problem")
pattern <- c("text", "some","be")
现在我想从 pattern
中删除文本中的所有元素,结果向量
text_result
[1] "this is"
[2] "elements should removed"
[3] "i hope you can help me with this element problem"
我试过了
text_result <- sapply(pattern, function(x) gsub(x, text, replacement =""))
或
text_result <- sapply(text, function(y) sapply(pattern, function(x)gsub(x,y,replacement ="")))
但在这两种情况下,我都会收到一个带有
的大矩阵
length(pattern)*length(text) elements
提前致谢!
你可以试试:
`%notin%` <- function(x,y) !(x %in% y)
lapply(strsplit(text," "),function(x) paste(x[x %notin% pattern],collapse=" "))
我觉得标题有点混乱,但我的问题是: 我有 2 个向量,一个包含一些文本,另一个包含一些短语
text <- c("this is some text","some elements should be removed", "i hope you can help me with this text element problem")
pattern <- c("text", "some","be")
现在我想从 pattern
中删除文本中的所有元素,结果向量
text_result
[1] "this is"
[2] "elements should removed"
[3] "i hope you can help me with this element problem"
我试过了
text_result <- sapply(pattern, function(x) gsub(x, text, replacement =""))
或
text_result <- sapply(text, function(y) sapply(pattern, function(x)gsub(x,y,replacement ="")))
但在这两种情况下,我都会收到一个带有
的大矩阵length(pattern)*length(text) elements
提前致谢!
你可以试试:
`%notin%` <- function(x,y) !(x %in% y)
lapply(strsplit(text," "),function(x) paste(x[x %notin% pattern],collapse=" "))