![](/img/trans.png)
[英]The condition has length > 1 and only the first element will be used. What changes to make?
[英]R Warning: the condition has length > 1 and only the first element will be used. outer function
我有以下两个功能:
name_fitting <- function(term1, term2)
{
if (nchar(term1) <= 3)
{
temp <- substring(term2, 1,nchar(term1))
return(temp==term1)
}
else {return(grepl(term1, term2))}
}
name_matching <- function(name1, name2)
{
name1 <- gsub('[[:punct:]]+','', name1)
name2 <- gsub('[[:punct:]]+','', name2)
if (length(intersect(as.character(unlist(strsplit(name1, ' '))), as.character(unlist(strsplit(name2, ' '))))) > 1) {return(TRUE)}
if (length(intersect(as.character(unlist(strsplit(name1, ' '))), as.character(unlist(strsplit(name2, ' '))))) == 1)
{
non_matching <- union(setdiff(as.character(unlist(strsplit(name1, ' '))), as.character(unlist(strsplit(name2, ' ')))), setdiff(as.character(unlist(strsplit(name2, ' '))), as.character(unlist(strsplit(name1, ' ')))))
temp <- outer(X = non_matching, Y = non_matching, FUN = 'name_fitting')
diag(temp)<-FALSE
return(any(temp))
}
else(return(FALSE))
}
name_fitting用于name_matching。 name_matching检查传递给函数的两个名称是否兼容并返回TRUE或FALSE。
当我尝试匹配两个名称时,如下所示:
name1<-"MARCO BRAMBILLA"
name2<-"M BRAMBILLA BRANDUARDI"
我收到以下警告:
条件的长度> 1,只使用第一个元素
指示外部函数未正确地将数据传递给name_fitting。
我该如何解决?
你的函数传递name_fitting字符向量non_matching
,它包含三个元素: [1] "MARCO" "M" "BRANDUARDI"
。 if (nchar(term1) <= 3)
该向量将传递给if
调用。 问题是nchar(term1) <= 3
给出了一个长度为3的向量: [1] FALSE TRUE FALSE
。
当然,问题是你想在这里实现的目标。 如果您要确定term1是否包含三个或更多元素,请将nchar
替换为length
。 如果您试图查看non_matching的任何元素是否为3个字符长或更短,请将nchar()调用放在any()
。 如果您尝试仅检查non_matching的第一个元素,则传递term1[1]
而不是term1
。
矢量化(功能)
是解决方案:
name_fitting <- function(term1, term2)
{
if (nchar(term1) <= 3)
{
temp <- substring(term2, 1,nchar(term1))
return(temp==term1)
}
else {return(grepl(term1, term2))}
}
name_fitting <- Vectorize(name_fitting)
name_matching <- function(name1, name2)
{
name1 <- trimws(gsub('[[:punct:]]+','', name1))
name2 <- trimws(gsub('[[:punct:]]+','', name2))
temp <- intersect(as.character(unlist(strsplit(name1, ' '))), as.character(unlist(strsplit(name2, ' '))))
temp <- temp[temp!=c('')]
if (length(temp) > 1) {return(TRUE)}
if (length(intersect(as.character(unlist(strsplit(name1, ' '))), as.character(unlist(strsplit(name2, ' '))))) == 1)
{
non_matching <- union(setdiff(as.character(unlist(strsplit(name1, ' '))), as.character(unlist(strsplit(name2, ' ')))), setdiff(as.character(unlist(strsplit(name2, ' '))), as.character(unlist(strsplit(name1, ' ')))))
non_matching <- non_matching[non_matching!=c("")]
temp <- outer(X = non_matching, Y = non_matching, FUN = 'name_fitting')
diag(temp)<-FALSE
return(any(temp))
}
else(return(FALSE))
}
name_matching <- Vectorize(name_matching)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.