我正在尝试在列表上进行匹配,但我无法从我的函数中获得一种输出。循环在vec [3]失败,这就是我使用trycatch的原因。但我仍然无法在我的功能输出中获得任何匹配。我无法输出任何东西。申请家庭也可以做同样的事情吗?
我试图匹配vec上的loc。 vec [3]会失败,因为我没有匹配。
vec=c('i am going to ooty corbett','i have to go to ooty', 'i have to go to manali')
loc=c('ooty','corbett')
out是我试图为比赛建立的矢量。
out=NULL
res_m=function(x,y){
out[i]=tryCatch(
{
for(i in 1:length(y)){
print(i)
x=tolower(x)
y=strsplit(y[i], " ")[[1]]
out[i]=intersect(x,y)
}
},error=function(cond) {
out[i]=NA
},
finally=print("can do")
)
return(out[i])
}
res=res_m(loc,vec)
使用ifelse,我得到了它的工作。但仍然可以从我的方法中找到解决方案。
res=NULL
out=NULL
for (i in 1:length(y)) {
print(i)
x = tolower(x)
z = strsplit(y[i], " ")[[1]]
out = intersect(x,z)
if (length(out) == 0) {
res[i] = NA
}else{
res[[i]] = out
}
}
答案 0 :(得分:1)
在你的res_m
中,你没有将“out”初始化为适当的对象,而且,你也覆盖了“y”:
res_m = function(x, y)
{
out = vector("list", length(y))
for(i in 1:length(y)) {
x = tolower(x)
yy = strsplit(y[i], " ")[[1]]
out[[i]] = intersect(x, yy)
}
return(out)
}
res_m(loc, vec)
#[[1]]
#[1] "ooty" "corbett"
#
#[[2]]
#[1] "ooty"
#
#[[3]]
#character(0)
您可以将tolower
和strsplit
移出您的循环:
res_m2 = function(x, y)
{
out = vector("list", length(y))
x = tolower(x)
y = strsplit(y, " ")
for(i in seq_along(y)) out[[i]] = intersect(x, y[[i]])
return(out)
}
res_m2(loc, vec)
#[[1]]
#[1] "ooty" "corbett"
#
#[[2]]
#[1] "ooty"
#
#[[3]]
#character(0)
或使用lapply
:
res_m3 = function(x, y)
{
x = tolower(x)
lapply(strsplit(y, " "), function(yy) intersect(x, yy))
}
res_m3(loc, vec)
#[[1]]
#[1] "ooty" "corbett"
#
#[[2]]
#[1] "ooty"
#
#[[3]]
#character(0)
如果 发生错误:
force_error = function(x, y)
{
out = vector("list", length(y))
x = tolower(x)
y = strsplit(y, " ")
for(i in seq_along(y))
tryCatch(expr = { out[i] = intersect(x, y[[i]]) },
error = function(e) {
cat(sprintf("error in in 'i = %d'\n --> %s\n", i, e))
out[i] <<- NA
},
warning = function(w) {
cat(sprintf("warning in in 'i = %d'\n --> %s\n", i, w))
out[i] <<- NA
})
return(out)
}
force_error(loc, vec)
#warning in in 'i = 1'
# --> simpleWarning in out[i] = intersect(x, y[[i]]): number of items to replace is not a multiple of replacement length
#
#error in in 'i = 3'
# --> Error in out[i] = intersect(x, y[[i]]): replacement has length zero
#
#[[1]]
#[1] NA
#
#[[2]]
#[1] "ooty"
#
#[[3]]
#[1] NA
或者,您可以使用
regmatches(vec, gregexpr(paste(loc, collapse = "|"), vec))
#[[1]]
#[1] "ooty" "corbett"
#
#[[2]]
#[1] "ooty"
#
#[[3]]
#character(0)