我正在思考如何让一个函数使用位于前面的线索词来选择最佳候选者。这应该是在字符串集中操作的,我尝试了很多次,但都没有成功。
基本概念是有这样一个字符串:‘- clueword (Candiate1|Candidate2...)-’,我想要的函数可以根据数据选择最有希望的候选者。
clue = c( 'a', 'to', 'a', 'to', 'to')
word = c('house','school','paper','water','schooling')
cooccur = c(100, 90, 83, 70, 61)
data = data.frame(clue,word,cooccur)假设有两个字符串集
S1 = 'I have a (house|water|paper) and car'
S2 = 'I need to go to (school|schooling) right now'提示词“a”与“house”同现的频率较高,“to”与“school”同现的频率较高。因此,使用该函数时,结果应该是
S1
[1] 'I have a (house) and car'
S2
[2] 'I need to go to (school) right now'您不需要担心删除前景不太好的候选对象,因为此代码会处理这些问题。
library(gsubfn)
gsubfn("\\(([^)]+)", ~paste0("(", paste(THEFUNCTION(unlist(x)), collapse="|")), S1)我知道我可以使用which.max(),但是使用它来处理“线索”一点都不容易。有什么办法能让我度过难关吗?
发布于 2017-02-03 15:57:06
这是可行的:
THEFUNCTION <- function(x) { # dummy function, to be replaced by the one that selects w.r.t. co-occurence frequency
# this function receives inputs without paranthesis: e.g., 'house|water|paper'
ifelse(grepl('house', x), 'house', 'school')
}
S1 = 'I have a (house|water|paper) and car'
S2 = 'I need to go to (school|schooling) right now'
library(gsubfn)
gsubfn("\\(([^\\)]+)\\)", ~paste0("(", paste(THEFUNCTION(unlist(x)), collapse="|"), ")"), S1)
#[1] "I have a (house) and car"
gsubfn("\\(([^\\)]+)\\)", ~paste0("(", paste(THEFUNCTION(unlist(x)), collapse="|"), ")"), S2)
#[1] "I need to go to (school) right now"https://stackoverflow.com/questions/42018937
复制相似问题